声明圆柱类 cylinder ,有数据成员圆半径 r 和高 h,成员函数有默认构造函数(默认半径为 1.5,高为 5.2)、计算圆柱体积函数,在主函数中用默认构造函数定义 1 个对象,并输出对象的体积。用 c++编写
时间: 2024-06-04 19:12:01 浏览: 20
#include <iostream>
using namespace std;
class cylinder {
private:
double r, h;
public:
cylinder(double r = 1.5, double h = 5.2) {
this->r = r;
this->h = h;
}
double volume() {
return 3.1415926 * r * r * h;
}
};
int main() {
cylinder c;
cout << "The volume of the cylinder is " << c.volume() << endl;
return 0;
}
相关问题
声明一个圆柱类,有数据成员底部半径radius、圆柱高height,成员函数volume()计算圆柱体的体积。构造一个cylinder的对象进行测试,由键盘输入半径和高,输出相应圆柱体的体积。
好的,以下是圆柱类的声明:
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。成员中私有数据成员半径和高,要求有构造函数,析构函数以及求圆柱体体积的成员函数,定义此类的两个对象,编写一个主函数进行测试
好的,我来给你解答这道题目。
首先,我们需要定义圆柱体类Cylinder,包含私有数据成员半径和高。代码如下:
```cpp
class Cylinder {
private:
double radius; // 半径
double height; // 高
public:
// 构造函数
Cylinder(double r = 0, double h = 0) {
radius = r;
height = h;
}
// 求圆柱体体积
double volume() {
return 3.14159 * radius * radius * height;
}
// 析构函数
~Cylinder() {}
};
```
其中,构造函数的参数有默认值,可以不传入参数。求圆柱体体积的公式为:πr²h。
接下来,我们需要定义两个对象并进行测试。代码如下:
```cpp
#include <iostream>
using namespace std;
int main() {
// 定义圆柱体对象
Cylinder c1(2, 5);
Cylinder c2(3, 4);
// 输出体积
cout << "c1的体积:" << c1.volume() << endl;
cout << "c2的体积:" << c2.volume() << endl;
return 0;
}
```
其中,我们创建了两个圆柱体对象c1和c2,并分别初始化了它们的半径和高。然后,我们分别输出了它们的体积。
完整代码如下: