用c++语言以矩形类作为基类,派生出长方体类Box。新增计算长方体 对象表面积和体积的功能。
时间: 2024-02-22 15:58:28 浏览: 76
好的,以下是用C++语言实现的代码:
```cpp
#include <iostream>
using namespace std;
class Rectangle {
protected:
double width, height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
}
double area() {
return width * height;
}
};
class Box : public Rectangle {
private:
double length;
public:
Box(double l, double w, double h) : Rectangle(w, h) {
length = l;
}
double volume() {
return length * width * height;
}
double surface_area() {
return 2 * (width * height + length * height + length * width);
}
};
int main() {
Box box(10, 20, 30);
cout << "Box volume: " << box.volume() << endl;
cout << "Box surface area: " << box.surface_area() << endl;
return 0;
}
```
在这个长方体类中,我们新增了两个方法,一个是计算长方体的体积(volume),另一个是计算长方体的表面积(surface_area)。计算表面积的公式是:2(wh + lh + lw),其中w、h、l分别表示长方体的宽度、高度和长度。
当我们需要计算长方体的体积和表面积时,我们只需要创建一个Box的对象,并调用它的volume和surface_area方法即可。例如:
```cpp
Box box(10, 20, 30);
cout << "Box volume: " << box.volume() << endl;
cout << "Box surface area: " << box.surface_area() << endl;
```
输出结果如下:
```
Box volume: 6000
Box surface area: 2200
```
这样,我们就成功地定义了一个长方体类,并新增了计算体积和表面积的功能。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)