)首先定义描述矩形的类Rectangle,其数据成员为矩形的长(Length)与宽(Width),成员函数为计算矩形面积的函数Area()与构造函数。然后由矩形类派生长方体类Cuboid,其数据成员为长方体的高High与体积Volume,成员函数为构造函数、计算体积的函数Vol(),以及显示长、宽、高与体积的函数Show()。主函数中用长方体类定义长方体对象cub,并为其赋初始值(10,20,30)。最后显示长方体的长、宽、高与体积。
时间: 2023-12-03 10:45:26 浏览: 69
以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class Rectangle {
protected:
double Length;
double Width;
public:
Rectangle(double l, double w) {
Length = l;
Width = w;
}
double Area() {
return Length * Width;
}
};
class Cuboid : public Rectangle {
protected:
double High;
double Volume;
public:
Cuboid(double l, double w, double h) : Rectangle(l, w) {
High = h;
Volume = Vol();
}
double Vol() {
return Length * Width * High;
}
void Show() {
cout << "Length = " << Length << endl;
cout << "Width = " << Width << endl;
cout << "High = " << High << endl;
cout << "Volume = " << Volume << endl;
}
};
int main() {
Cuboid cub(10, 20, 30);
cub.Show();
return 0;
}
```
运行结果:
```
Length = 10
Width = 20
High = 30
Volume = 6000
```
阅读全文