C++程序设计 急 急 急
- 提问者网友:做自己de王妃
- 2021-05-15 11:37
- 五星知识达人网友:鱼芗
- 2021-05-15 12:45
代码如下,你先看看:
#include<iostream>
using namespace std;
class Container {
public:
double radius;
virtual double area() = 0; // 返回表面积结果
virtual double volume() = 0; // 返回体积结果
};
// 正方体类
class Cube : public Container {
public:
Cube(double radius) {
this->radius = radius;
}
double area() {
return (6 * radius * radius);
}
double volume() {
return (radius * radius * radius);
}
};
// 球体类
class Sphere : public Container {
public:
Sphere(double radius) {
this->radius = radius;
}
double area() {
return (4 * 3.1415 * radius * radius);
}
double volume() {
return (4 * 3.1415 * radius * radius * radius / 3);
}
};
// 圆柱体类
class Cylilnder : public Container {
public:
Cylilnder(double radius) {
this->radius = radius;
}
double area() {
return (2 * 3.1415 * radius * radius + 2 * 3.1415 * radius * radius);
}
double volume() {
return (3.1415 * radius * radius * radius);
}
};
int main() {
Container *cube = new Cylilnder(1.0);
cout << cube->area() << " --- " << cube->volume() << endl;
return 0;
}
// main函数里面用到多态,可将Cylilnder换成任意子类类名
- 1楼网友:拾荒鲤
- 2021-05-15 13:03
int main() {
Container *cube = new Cylilnder(1.0);
cout << cube->area() << " --- " << cube->volume() << endl;
Container *Shape; Cube A(5); Shape=&A; cout<<Shape->volume()<<"---"<<Shape->area()<<endl;
return 0;
}
应该是虚基类去定义一个指针后才可以指向其他派生类呀,像我的例子