声明一个圆柱类,有数据成员底部半径radius、圆柱高height,成员函数volume()计算圆柱体的体积。构造一个cylinder的对象进行测试,由键盘输入半径和高,输出相应圆柱体的体积。
时间: 2023-04-27 07:03:01 浏览: 101
好的,以下是圆柱类的声明:
class Cylinder {
private:
double radius; // 底部半径
double height; // 圆柱高
public:
Cylinder(double r, double h); // 构造函数
double volume(); // 计算圆柱体积的成员函数
};
构造函数的定义如下:
Cylinder::Cylinder(double r, double h) {
radius = r;
height = h;
}
计算圆柱体积的成员函数的定义如下:
double Cylinder::volume() {
return 3.14 * radius * radius * height;
}
接下来,我们可以构造一个cylinder的对象进行测试,代码如下:
int main() {
double r, h;
cout << "请输入圆柱的底部半径和高:";
cin >> r >> h;
Cylinder cylinder(r, h);
cout << "圆柱体积为:" << cylinder.volume() << endl;
return 0;
}
以上代码中,我们先从键盘输入圆柱的底部半径和高,然后构造一个cylinder的对象,并调用其volume()函数计算圆柱体积,最后输出结果。
相关问题
定义一个圆柱体类Cylinder,类内数据成员有radius(圆柱体底面半径)、height(圆柱体高度),成员函数有构造函数、surface和volume。surface函数实现计算圆柱体的表面积,volume实现计算圆柱体的体积。在main函数中定义Cylinder类的对象c,并调用surface函数计算对象c的表面积,调用volume计算对象c的体积。
下面是一个实现上述要求的示例代码:
```cpp
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius;
double height;
public:
Cylinder(double r = 0, double h = 0) : radius(r), height(h) {}
double surface() {
return 2 * 3.1416 * radius * (radius + height);
}
double volume() {
return 3.1416 * radius * radius * height;
}
};
int main() {
double r, h;
cout << "Enter radius and height of cylinder: ";
cin >> r >> h;
Cylinder c(r, h);
cout << "Surface area of cylinder: " << c.surface() << endl;
cout << "Volume of cylinder: " << c.volume() << endl;
return 0;
}
```
在上面的示例代码中,我们定义了一个 `Cylinder` 类,其中包含 `radius` 和 `height` 两个私有数据成员,分别表示圆柱体的底面半径和高度。类中还定义了一个构造函数,用于初始化 `Cylinder` 对象的数据成员。另外,类中还实现了 `surface` 和 `volume` 两个成员函数,分别用于计算圆柱体的表面积和体积。
在 `main` 函数中,我们首先通过用户输入获得圆柱体的底面半径和高度,然后定义了一个 `Cylinder` 类的对象 `c`,并使用 `c.surface()` 和 `c.volume()` 分别计算了 `c` 的表面积和体积,并输出到屏幕上。
定义一个圆柱体类Cylindet。成员中有私有数据成员半径和高,要求有构造函数,析构函数以及求圆柱体体积的成员函数。定义此类的两个对象,编写一个主函数进行测试。
好的,这是一个典型的面向对象编程问题,下面是C++的代码实现:
```
#include<iostream>
using namespace std;
class Cylinder{
private:
double radius; // 圆柱体底面半径
double height; // 圆柱体高
public:
// 构造函数
Cylinder(double r, double h){
radius = r;
height = h;
}
// 求圆柱体体积的成员函数
double getVolume(){
return 3.14 * radius * radius * height;
}
// 析构函数
~Cylinder(){
cout << "Cylinder destroyed." << endl;
}
};
int main(){
// 定义两个圆柱体对象
Cylinder c1(3.5, 4.0);
Cylinder c2(4.5, 5.0);
// 输出圆柱体的体积
cout << "Volume of c1: " << c1.getVolume() << endl;
cout << "Volume of c2: " << c2.getVolume() << endl;
return 0;
}
```
在上面的代码中,我们定义了一个Cylinder类,该类有私有数据成员radius和height,以及公有的构造函数、析构函数和成员函数getVolume()。构造函数用于初始化半径和高,析构函数用于释放对象占用的内存。getVolume()函数用于计算圆柱体的体积,并返回结果。
在主函数中,我们定义了两个圆柱体对象c1和c2,并分别输出它们的体积。运行结果如下:
```
Volume of c1: 153.86
Volume of c2: 318.31
Cylinder destroyed.
Cylinder destroyed.
```
从输出结果可以看出,程序正确地计算并输出了两个圆柱体的体积,并在程序结束时自动调用了析构函数释放内存。