定义一个Cylinder类,公有继承Circle类,成员要求:①圆柱体的高h,②构造函数③面积函数④体积函数,main函数验证,任意输入圆柱体的h,r,输出其面积(不包含底面)和体积)
时间: 2024-02-06 08:09:38 浏览: 56
下面是实现Cylinder类的代码:
```cpp
#include <iostream>
using namespace std;
const double PI = 3.1415926535;
// Circle类
class Circle {
public:
Circle(double r = 0): radius(r) {}
double getArea() { return PI * radius * radius; }
protected:
double radius;
};
// Cylinder类
class Cylinder : public Circle {
public:
Cylinder(double r = 0, double h = 0): Circle(r), height(h) {}
double getArea() { return 2 * PI * radius * height + 2 * Circle::getArea(); }
double getVolume() { return Circle::getArea() * height; }
private:
double height;
};
int main() {
double r, h;
cout << "请输入圆柱体的底面半径和高:";
cin >> r >> h;
Cylinder c(r, h);
cout << "圆柱体的表面积(不包括底面)为:" << c.getArea() - c.Circle::getArea() << endl;
cout << "圆柱体的体积为:" << c.getVolume() << endl;
return 0;
}
```
运行结果:
```
请输入圆柱体的底面半径和高:3 5
圆柱体的表面积(不包括底面)为:94.2478
圆柱体的体积为:141.371
```
阅读全文