c++定义一个可以计算圆的面积与周长的基类,再定义一个可以计算圆柱体的体积和表面积的派生类。
时间: 2023-08-21 13:06:38 浏览: 43
以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Circle {
protected:
double radius;
public:
Circle(double r): radius(r){}
double get_area() {
return 3.14159 * radius * radius;
}
double get_perimeter() {
return 2 * 3.14159 * radius;
}
};
class Cylinder: public Circle {
private:
double height;
public:
Cylinder(double r, double h): Circle(r), height(h){}
double get_volume() {
return get_area() * height;
}
double get_surface_area() {
return 2 * get_area() + get_perimeter() * height;
}
};
int main() {
Cylinder c(2, 5);
cout << "Surface area of the cylinder is: " << c.get_surface_area() << endl;
cout << "Volume of the cylinder is: " << c.get_volume() << endl;
return 0;
}
```
在这个例子中,我们定义了一个名为 `Circle` 的基类,它包含了圆的半径和计算圆的面积和周长的方法。接着,我们创建了一个名为 `Cylinder` 的派生类,它继承了 `Circle` 类,包含了圆柱体的高度和计算圆柱体体积和表面积的方法。在 `main` 函数中,我们创建了一个 `Cylinder` 对象,并调用了它的方法来计算表面积和体积。