编写一个球体Ball类,数据成员有半径,成员函数有构造函数、求体积函数,求表面积函数编写主函数创建两个球对象,计算这两个球体的体积和表面积,并输出每个球体的体积和表面积。
时间: 2024-03-10 14:46:04 浏览: 51
好的,以下是实现代码:
```cpp
#include <iostream>
using namespace std;
class Ball {
private:
double radius;
public:
Ball(double r) : radius(r) {} // 构造函数
double getVolume() { // 求体积
return 4.0 / 3.0 * 3.14159 * radius * radius * radius;
}
double getSurfaceArea() { // 求表面积
return 4.0 * 3.14159 * radius * radius;
}
};
int main() {
Ball ball1(3.0);
Ball ball2(4.0);
cout << "Ball 1: volume = " << ball1.getVolume()
<< ", surface area = " << ball1.getSurfaceArea() << endl;
cout << "Ball 2: volume = " << ball2.getVolume()
<< ", surface area = " << ball2.getSurfaceArea() << endl;
cout << "The sum of volumes = " << ball1.getVolume() + ball2.getVolume() << endl;
cout << "The sum of surface areas = " << ball1.getSurfaceArea() + ball2.getSurfaceArea() << endl;
return 0;
}
```
输出结果如下:
```
Ball 1: volume = 113.097, surface area = 113.097
Ball 2: volume = 268.082, surface area = 201.062
The sum of volumes = 381.179
The sum of surface areas = 314.159
```
阅读全文