编写程序,定义具有继承关系的圆和圆柱体类,前者的数据成员中包含半径,函数成员包含计算圆面积,后者的数据成员有圆柱体高度,函数成员有计算表面积和体积,两类中都包含显示参数的函数。
时间: 2023-06-05 07:47:55 浏览: 95
好的,以下是编写程序,定义具有继承关系的圆和圆柱体类的代码:
```c++
#include <iostream>
using namespace std;
const double PI = 3.14159265358979323846;
class Circle {
protected:
double radius;
public:
Circle(double r) : radius(r) {}
double getRadius() const { return radius; }
void setRadius(double r) { radius = r; }
double getArea() const { return PI * radius * radius; }
void display() const {
cout << "Radius: " << radius << endl;
cout << "Area: " << getArea() << endl;
}
};
class Cylinder : public Circle {
private:
double height;
public:
Cylinder(double r, double h) : Circle(r), height(h) {}
double getHeight() const { return height; }
void setHeight(double h) { height = h; }
double getSurfaceArea() const { return 2 * PI * radius * height + 2 * getArea(); }
double getVolume() const { return getArea() * height; }
void display() const {
cout << "Radius: " << radius << endl;
cout << "Height: " << height << endl;
cout << "Surface Area: " << getSurfaceArea() << endl;
cout << "Volume: " << getVolume() << endl;
}
};
int main() {
Circle c(5);
c.display();
Cylinder cy(3, 7);
cy.display();
return ;
}
```
以上代码定义了两个类:`Circle` 和 `Cylinder`,其中 `Cylinder` 继承自 `Circle`。`Circle` 类包含一个数据成员 `radius`,表示圆的半径,以及三个函数成员:`getRadius()`,`setRadius()` 和 `getArea()`,分别用于获取半径、设置半径和计算圆面积。`Cylinder` 类在 `Circle` 类的基础上增加了一个数据成员 `height`,表示圆柱体的高度,以及三个函数成员:`getHeight()`,`setHeight()`,`getSurfaceArea()` 和 `getVolume()`,分别用于获取高度、设置高度、计算表面积和计算体积。两个类中都包含一个 `display()` 函数,用于显示参数。
在 `main()` 函数中,我们创建了一个 `Circle` 对象和一个 `Cylinder` 对象,并分别调用了它们的 `display()` 函数,以显示它们的参数。