C++已知圆类,派生出圆柱类,求圆柱体积,表面积
时间: 2024-01-25 12:10:50 浏览: 134
求圆柱的底面积表面积C++源码
以下是C++已知圆类,派生出圆柱类,求圆柱体积和表面积的示例代码:
```cpp
#include <iostream>
using namespace std;
// 定义圆类
class Circle {
protected:
double radius; // 半径
public:
Circle(double r) : radius(r) {}
double getArea() { return 3.14 * radius * radius; } // 求圆面积
};
// 定义圆柱类
class Cylinder : public Circle {
private:
double height; // 高
public:
Cylinder(double r, double h) : Circle(r), height(h) {}
double getVolume() { return getArea() * height; } // 求圆柱体积
double getSurfaceArea() { return 2 * getArea() + 2 * 3.14 * radius * height; } // 求圆柱表面积
};
int main() {
double r, h;
cout << "请输入圆柱的半径和高:" << endl;
cin >> r >> h;
Cylinder c(r, h);
cout << "圆柱的体积为:" << c.getVolume() << endl;
cout << "圆柱的表面积为:" << c.getSurfaceArea() << endl;
return 0;
}
```
阅读全文