使用虚函数编写程序,求球体和圆柱体的面积
时间: 2024-01-23 17:44:57 浏览: 30
以下是使用虚函数编写求球体和圆柱体面积的程序:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 定义基类Shape
class Shape {
public:
virtual double getArea() = 0; // 声明虚函数getArea
};
// 定义派生类Sphere,表示球体
class Sphere : public Shape {
private:
double radius; // 球体半径
public:
Sphere(double r) : radius(r) {} // 构造函数
double getArea() { return 4 * M_PI * radius * radius; } // 实现虚函数getArea,计算球体面积
};
// 定义派生类Cylinder,表示圆柱体
class Cylinder : public Shape {
private:
double radius; // 圆柱体底面半径
double height; // 圆柱体高
public:
Cylinder(double r, double h) : radius(r), height(h) {} // 构造函数
double getArea() { return 2 * M_PI * radius * height + 2 * M_PI * radius * radius; } // 实现虚函数getArea,计算圆柱体面积
};
int main() {
Sphere s(5); // 创建球体对象
Cylinder c(3, 10); // 创建圆柱体对象
// 分别调用虚函数getArea计算面积并输出
cout << "球体面积:" << s.getArea() << endl;
cout << "圆柱体面积:" << c.getArea() << endl;
return 0;
}
```
输出结果为:
```
球体面积:314.159
圆柱体面积:188.496
```