【问题描述】定义一个长方形Rect类,派生出长方体类Cub,计算派生类对象(长方体)的表面积和体积。
【输入形式】长方体对象的长、宽、高。
【输出形式】输出该长方体的表面积和体积。
【样例输入】
输入长方体的长、宽、高:1.2 2.5 3.8
【样例输出】
length=1.2 width=2.5 height=3.8
表面积=34.12 体积=11.4
代码如下:
#include <iostream>
using namespace std;
// 定义长方形Rect类
class Rect {
public:
double length;
double width;
double area;
Rect(double l, double w) {
length = l;
width = w;
area = length * width;
}
};
// 派生出长方体类Cub
class Cub : public Rect {
public:
double height;
double volume;
double surfaceArea;
Cub(double l, double w, double h) : Rect(l,w) {
height = h;
volume = area * height;
surfaceArea = 2 * (length*width + length*height + width*height);
}
};
int main() {
double l, w, h;
cout << "输入长方体的长、宽、高:"<<endl;
cin >> l >> w >> h;
Cub c(l, w, h);
cout << "length=" << c.length << " width=" << c.width << " height=" << c.height << endl;
cout << "表面积=" << c.surfaceArea << " 体积=" << c.volume << endl;
return 0;
}