定义一个抽象基类(Shape),含有一个数据成员半径(-,并设为保护成员:定义返回 表面积(surfaceArea)和返回体积(volume)的成员函数,这些西数都是纯虚西数。定义基 类的派生 类球(Ba下)、圆柱(Cyinder),都含有返口表面积(surfacearea)和返回体积Cvolume) 的成员西数:圆桂(Cvinder)类还应增加一个私有数据成员高度 Cheight)。编写主文件, 进行测试,求球、圆柱的表面积和体积。使用基类指针,通过基类指针调用具体的派生类对 象中的面积和体积计算函数,实现面积和体积的计算,并输出结果。
时间: 2023-12-10 16:42:41 浏览: 105
C抽象基类和纯虚成员函数-C教程共3页.pdf.zip
以下是题目要求的抽象基类Shape及其派生类的实现:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
double radius;
public:
Shape(double r = 0) : radius(r) {}
virtual double surfaceArea() = 0;
virtual double volume() = 0;
};
class Ball : public Shape {
public:
Ball(double r) : Shape(r) {}
virtual double surfaceArea() {
return 4 * 3.14 * radius * radius;
}
virtual double volume() {
return 4.0 / 3.0 * 3.14 * radius * radius * radius;
}
};
class Cylinder : public Shape {
private:
double height;
public:
Cylinder(double r, double h) : Shape(r), height(h) {}
virtual double surfaceArea() {
return 2 * 3.14 * radius * radius + 2 * 3.14 * radius * height;
}
virtual double volume() {
return 3.14 * radius * radius * height;
}
};
int main() {
Shape* p;
Ball b(5);
Cylinder c(3, 10);
p = &b;
cout << "Ball surface area: " << p->surfaceArea() << endl;
cout << "Ball volume: " << p->volume() << endl;
p = &c;
cout << "Cylinder surface area: " << p->surfaceArea() << endl;
cout << "Cylinder volume: " << p->volume() << endl;
return 0;
}
```
输出结果为:
```
Ball surface area: 314
Ball volume: 523.333
Cylinder surface area: 207.36
Cylinder volume: 282.6
```
阅读全文