设计矩形和立方体面积和体积的类c++
时间: 2023-06-01 17:06:07 浏览: 105
用C++设计一个立方体类Box,它能计算并输出立方体的体积和表面积,并编写main函数测试该类。
4星 · 用户满意度95%
很好,这是一个和数学相关的问题,我可以回答这个问题。以下是设计矩形和立方体面积和体积的类c的示例代码:
```
class Geometry {
public:
float area(float length, float width) { return length * width; }
float volume(float length, float width, float height) { return length * width * height; }
};
class Rectangle {
private:
float length;
float width;
public:
Rectangle(float l, float w) {
this->length = l;
this->width = w;
}
float getArea() {
Geometry g;
return g.area(length, width);
}
};
class Cube {
private:
float length;
float width;
float height;
public:
Cube(float l, float w, float h) {
this->length = l;
this->width = w;
this->height = h;
}
float getVolume() {
Geometry g;
return g.volume(length, width, height);
}
};
int main() {
Rectangle r(5, 10);
Cube c(4, 4, 4);
std::cout << "The area of the rectangle is: " << r.getArea() << std::endl;
std::cout << "The volume of the cube is: " << c.getVolume() << std::endl;
return 0;
}
```
这个类可以计算矩形的面积和立方体的体积,你可以根据自己的需求进行调整。感谢您的提问!
阅读全文