c++ 编程 Define a class Circle and derive the class Cylinder from the class Circle. The specific requirements are as follows: In the main function, input the radius of the circle and output the area of the corresponding circle. Then, input the height of the cylinder, output the surface area and volume of the corresponding cylinder.
时间: 2024-02-20 18:01:59 浏览: 232
【嵌入式学习】Keil5 链接报错: No space in execution regions with .ANY selector 解决方案
下面是一个符合您要求的 C++ 代码实现:
```cpp
#include<iostream>
using namespace std;
class Circle {
protected:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const {
return 3.14 * radius * radius;
}
};
class Cylinder : public Circle {
private:
double height;
public:
Cylinder(double r, double h) : Circle(r), height(h) {}
double getSurfaceArea() const {
return 2 * 3.14 * radius * height + 2 * Circle::getArea();
}
double getVolume() const {
return Circle::getArea() * height;
}
};
int main() {
double r, h;
cout << "Please input the radius of the circle: ";
cin >> r;
Circle c(r);
cout << "The area of the corresponding circle is: " << c.getArea() << endl;
cout << "Please input the height of the cylinder: ";
cin >> h;
Cylinder cy(r, h);
cout << "The surface area of the corresponding cylinder is: " << cy.getSurfaceArea() << endl;
cout << "The volume of the corresponding cylinder is: " << cy.getVolume() << endl;
return 0;
}
```
在这个代码实现中,我们定义了一个圆形类 Circle,它有一个受保护的成员变量 radius 和一个公有函数 getArea(),返回圆形的面积。然后我们从 Circle 类派生出一个圆柱体类 Cylinder,它有一个私有成员变量 height 和两个公有函数 getSurfaceArea() 和 getVolume(),分别返回圆柱体的表面积和体积。在 main() 函数中,我们首先输入圆形的半径,创建一个 Circle 对象并输出其面积。然后输入圆柱体的高度,创建一个 Cylinder 对象并输出其表面积和体积。
阅读全文