写一个程序,定义抽象基类Container,由它派生出3个派生类:Sphere(球体) Cylinder(圆柱体)、Cube(正方体)。用虚函数分别计算几种图形的表面积和体积。
时间: 2024-02-17 22:02:15 浏览: 105
好的,下面是代码实现:
```
#include<iostream>
using namespace std;
class Container {
public:
virtual double getVolume() = 0;
virtual double getArea() = 0;
};
class Sphere : public Container {
private:
double radius;
public:
Sphere(double r) : radius(r) {}
virtual double getVolume() {
return 4.0 / 3.0 * 3.1415926 * radius * radius * radius;
}
virtual double getArea() {
return 4.0 * 3.1415926 * radius * radius;
}
};
class Cylinder : public Container {
private:
double radius, height;
public:
Cylinder(double r, double h) : radius(r), height(h) {}
virtual double getVolume() {
return 3.1415926 * radius * radius * height;
}
virtual double getArea() {
return 2.0 * 3.1415926 * radius * height + 2.0 * 3.1415926 * radius * radius;
}
};
class Cube : public Container {
private:
double side;
public:
Cube(double s) : side(s) {}
virtual double getVolume() {
return side * side * side;
}
virtual double getArea() {
return 6.0 * side * side;
}
};
int main() {
Container* c1 = new Sphere(5.0);
Container* c2 = new Cylinder(5.0, 10.0);
Container* c3 = new Cube(5.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,实现这两个纯虚函数。最后在主函数中创建这三个类的对象,分别调用其计算体积和表面积的函数进行输出。
阅读全文