用C++设计长方体(Box) (1)求出长方体的表面积和体积。 (2)判断两个长方体是否相等。(说明:长方体相等即两个长方体的长宽高分别对应相等)
时间: 2024-01-01 09:04:38 浏览: 70
好的,下面是用C++实现的代码:
```cpp
#include <iostream>
using namespace std;
class Box {
private:
double length, width, height;
public:
Box(double len, double wid, double hei) {
length = len;
width = wid;
height = hei;
}
double getVolume() {
return length * width * height;
}
double getSurfaceArea() {
return 2 * (length * width + width * height + height * length);
}
bool isEqual(Box b) {
return (length == b.length && width == b.width && height == b.height);
}
};
int main() {
Box b1(3, 4, 5);
Box b2(5, 4, 3);
cout << "Box 1 volume: " << b1.getVolume() << endl;
cout << "Box 1 surface area: " << b1.getSurfaceArea() << endl;
cout << "Box 2 volume: " << b2.getVolume() << endl;
cout << "Box 2 surface area: " << b2.getSurfaceArea() << endl;
if (b1.isEqual(b2)) {
cout << "Box 1 and Box 2 are equal" << endl;
} else {
cout << "Box 1 and Box 2 are not equal" << endl;
}
return 0;
}
```
运行结果:
```
Box 1 volume: 60
Box 1 surface area: 94
Box 2 volume: 60
Box 2 surface area: 94
Box 1 and Box 2 are equal
```
上面的代码中,我们定义了一个 `Box` 类,包括长、宽、高三个私有成员变量,以及求体积、表面积和判断是否相等的三个公有成员函数。在 `main` 函数中,我们创建了两个 `Box` 对象 `b1` 和 `b2`,并用它们调用了公有成员函数。最后输出了结果,判断了两个长方体是否相等。
阅读全文