写一个C++程序,定义抽象基类Coutainer,由它派生出3个派生类:Sphere(球体),Cylinder(圆柱体),Cube(正方体)。用虚函数分别计算几种图形的表面积和体积
时间: 2024-03-24 11:36:04 浏览: 95
好的,以下是程序代码:
```c++
#include <iostream>
using namespace std;
// 定义抽象基类Container
class Container {
public:
virtual double getVolume() = 0; // 纯虚函数,计算体积
virtual double getArea() = 0; // 纯虚函数,计算表面积
};
// 派生类Sphere,计算球体的表面积和体积
class Sphere : public Container {
public:
Sphere(double r) : radius(r) {}
virtual double getVolume() { return 4.0 / 3.0 * 3.14 * radius * radius * radius; }
virtual double getArea() { return 4.0 * 3.14 * radius * radius; }
private:
double radius; // 球体半径
};
// 派生类Cylinder,计算圆柱体的表面积和体积
class Cylinder : public Container {
public:
Cylinder(double r, double h) : radius(r), height(h) {}
virtual double getVolume() { return 3.14 * radius * radius * height; }
virtual double getArea() { return 2.0 * 3.14 * radius * height + 2.0 * 3.14 * radius * radius; }
private:
double radius; // 圆柱体底面半径
double height; // 圆柱体高
};
// 派生类Cube,计算正方体的表面积和体积
class Cube : public Container {
public:
Cube(double a) : edge(a) {}
virtual double getVolume() { return edge * edge * edge; }
virtual double getArea() { return 6.0 * edge * edge; }
private:
double edge; // 正方体棱长
};
int main() {
Container *c1 = new Sphere(2.0);
Container *c2 = new Cylinder(2.0, 3.0);
Container *c3 = new Cube(2.0);
cout << "Sphere volume: " << c1->getVolume() << endl;
cout << "Sphere area: " << c1->getArea() << endl;
cout << "Cylinder volume: " << c2->getVolume() << endl;
cout << "Cylinder area: " << c2->getArea() << endl;
cout << "Cube volume: " << c3->getVolume() << endl;
cout << "Cube area: " << c3->getArea() << endl;
delete c1;
delete c2;
delete c3;
return 0;
}
```
程序中,抽象基类`Container`定义了两个纯虚函数`getVolume`和`getArea`,分别用于计算图形的体积和表面积。`Sphere`、`Cylinder`和`Cube`分别继承了`Container`类,并重写了`getVolume`和`getArea`纯虚函数,实现了对球体、圆柱体、正方体的体积和表面积计算。在`main`函数中分别创建了这三个派生类的对象,并输出了它们的体积和表面积。最后,释放了动态分配的内存。
阅读全文