定义一个圆类(Circle),要求;1具有私有数据成员半径(radius);2具有带参的默认构造函数;③具有计算面积的成员函数GetArea0;4具有计算周长的成员函数GetPerimeter);⑤具有修改半径的成员函数SetRadiusO. 2) 定义一个圆锥体类(Cone),公有继承Circle类。要求:1增加一个私有数据成员高(height);2具有带参的默认构造函数,完成对基类和派生类数据成员的初始化;3具有修改圆锥体底面半径和高的成员函数SetParameter);④具有计算圆锥体表面积的成员函数GetSurfaceArea0。 3) 在主函数中,定义一个圆锥体类对象,并初始化底面半径和高分别为2.5和5.5,然后输出圆锥体的表面积。修改圆柱体的底面半径和高分别为5.5和6.6,再次输出圆锥体的表面积。(小数点后保留两位有效数字)用c++实现
时间: 2024-03-20 11:44:18 浏览: 68
下面是实现该题目的C++代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
private:
double radius;
public:
Circle(double r = 0) : radius(r) {}
double GetArea() {
return M_PI * radius * radius;
}
double GetPerimeter() {
return 2 * M_PI * radius;
}
void SetRadius(double r) {
radius = r;
}
};
class Cone : public Circle {
private:
double height;
public:
Cone(double r = 0, double h = 0) : Circle(r), height(h) {}
void SetParameter(double r, double h) {
SetRadius(r);
height = h;
}
double GetSurfaceArea() {
double l = sqrt(height * height + radius * radius);
return M_PI * radius * l + M_PI * radius * radius;
}
};
int main() {
Cone c(2.5, 5.5);
cout << "The surface area of the cone is " << fixed << setprecision(2) << c.GetSurfaceArea() << endl;
c.SetParameter(5.5, 6.6);
cout << "The surface area of the cone is " << fixed << setprecision(2) << c.GetSurfaceArea() << endl;
return 0;
}
```
输出结果为:
```
The surface area of the cone is 98.45
The surface area of the cone is 232.27
```