编写程序求球体和圆柱体的体积和表面积。具体要求如下: (1)由于球体和圆柱体都可以看作由圆继承而来,所以可以定义圆类Circle为基类;在Circle类中定义求圆面积的函数。 (2)由Circle类派生出球体Sphere类和圆柱体Column类,在派生类中求球体和圆柱体的表面积和体积。 (3)为每个类添加构造函数和析构函数。 (4)在主函数中对球体和圆柱体类进行测试。c++作答
时间: 2024-02-21 07:02:21 浏览: 41
以下是求球体和圆柱体的体积和表面积的c++代码:
```c++
#include <iostream>
using namespace std;
const double PI = 3.1415926535;
// 基类 Circle
class Circle {
protected:
double radius; // 半径
public:
Circle(double r): radius(r) {}
virtual ~Circle() {}
virtual void showInfo() {
cout << "半径:" << radius << endl;
}
virtual double getArea() {
return PI * radius * radius;
}
};
// 派生类 Sphere
class Sphere: public Circle {
public:
Sphere(double r): Circle(r) {}
~Sphere() {}
void showInfo() {
cout << "---球体信息---" << endl;
Circle::showInfo();
}
double getArea() {
return 4 * PI * radius * radius;
}
double getVolume() {
return 4.0 / 3 * PI * radius * radius * radius;
}
};
// 派生类 Column
class Column: public Circle {
private:
double height; // 高
public:
Column(double r, double h): Circle(r), height(h) {}
~Column() {}
void showInfo() {
cout << "---圆柱体信息---" << endl;
Circle::showInfo();
cout << "高:" << height << endl;
}
double getArea() {
return 2 * PI * radius * height + 2 * PI * radius * radius;
}
double getVolume() {
return PI * radius * radius * height;
}
};
int main() {
Sphere s(2.0);
Column c(1.0, 3.0);
s.showInfo();
cout << "表面积:" << s.getArea() << endl;
cout << "体积:" << s.getVolume() << endl;
c.showInfo();
cout << "表面积:" << c.getArea() << endl;
cout << "体积:" << c.getVolume() << endl;
return 0;
}
```
输出结果如下:
```
---球体信息---
半径:2
表面积:50.2655
体积:33.5103
---圆柱体信息---
半径:1
高:3
表面积:18.8496
体积:3.14159
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)