文章
225
粉丝
165
获赞
361
访问
107.3k
#include <iostream>
using namespace std;
// 长方形基类
class rectangle {
protected:
int length; // 长
int width; // 宽
public:
// 构造函数
rectangle(int l, int w) : length(l), width(w) {}
// 计算长方形面积(即长方体底面积)
int area() const {
return length * width;
}
};
// 长方体派生类,继承长方形类
class cuboid : public rectangle {
private:
int height; // 高
public:
// 构造函数,初始化基类的长和宽,再初始化自身的高
cuboid(int l, int w, int h) : rectangle(l, w), height(h) {}
// 重写area方法,计算长方体表面积
int area() const {
return 2 * (length * width + length * height + width * height);
}
};
int main() {
int x, y, z;
cin >> x >> y >> z; // 输入长、宽、高
cuboid cb(x, y, z); // 创建长方体对象
// 输出底面积(调用基类的area方法)
cout << cb.rectangle::area() << endl;
// 输出表面积(调用派生类重写的area方法)
cout << cb.area() << endl;
return 0;
}
登录后发布评论
暂无评论,来抢沙发