定义一个Cylinder类,公有继承Circle类,成员要求:①圆柱体的高h,②构造函数③面积函数④体积函数,main函数验证,任意输入圆柱体的h,r,输出其面积(不包含底面)和体积)
时间: 2024-02-06 09:09:13 浏览: 25
以下是定义Cylinder类的代码:
```c++
#include<iostream>
using namespace std;
class Circle{
protected:
double r; // 圆的半径
public:
Circle(double r):r(r){} // 构造函数
double area(){return 3.14 * r * r;} // 面积函数
};
class Cylinder: public Circle{
private:
double h; // 圆柱体的高
public:
Cylinder(double r, double h):Circle(r),h(h){} // 构造函数
double area(){return 2 * Circle::area() + 2 * 3.14 * r * h;} // 面积函数
double volume(){return Circle::area() * h;} // 体积函数
};
int main(){
double r, h;
cout << "请输入圆柱体的半径和高:" << endl;
cin >> r >> h;
Cylinder c(r, h);
cout << "圆柱体的面积(不包括底面)为:" << c.area() - c.Circle::area() << endl;
cout << "圆柱体的体积为:" << c.volume() << endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个Circle类,其中包含了圆的半径和面积,然后我们通过公有继承,在Cylinder类中继承了Circle类,同时添加了圆柱体的高h。在Cylinder类中,我们重载了Circle类的面积函数,并添加了一个体积函数。
在main函数中,我们首先获取用户输入的半径和高,然后创建一个Cylinder对象c,最后输出圆柱体的面积(不包括底面)和体积。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)