主函数生成一个圆柱体对象数组
时间: 2023-11-03 07:05:42 浏览: 46
好的,我理解了你的问题。以下是一个主函数生成一个圆柱体对象数组的示例代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Cylinder {
public:
Cylinder(double r, double h) : radius(r), height(h) {} // 构造函数
double getVolume() const { // 返回圆柱体体积
return M_PI * pow(radius, 2) * height;
}
private:
double radius; // 圆柱体半径
double height; // 圆柱体高度
};
int main() {
const int numCylinders = 5;
Cylinder cylinders[numCylinders] = { // 创建圆柱体对象数组
Cylinder(1.0, 2.0),
Cylinder(2.0, 3.0),
Cylinder(3.0, 4.0),
Cylinder(4.0, 5.0),
Cylinder(5.0, 6.0)
};
for (int i = 0; i < numCylinders; ++i) { // 输出每个圆柱体的体积
cout << "Cylinder " << i+1 << " volume: " << cylinders[i].getVolume() << endl;
}
return 0;
}
```
这个程序创建了一个包含5个圆柱体对象的数组,每个圆柱体都有不同的半径和高度。主函数遍历数组并输出每个圆柱体的体积。注意,这里使用了cmath库中的M_PI来表示圆周率。