设计一个CShape基类,由CShape类派生出矩形类CRectangle。再由矩形类CRectangle派生出长方体类CCuboid,设计不属于这些类的Display函数,用来输出CRectangle和CCuboid对象的周长和面积。根据下面的测试程序设计这些类及函数Display。请自行补充所涉及的头文件。
时间: 2024-02-05 11:12:20 浏览: 100
按以下描述和要求建立两个类:基类 Rectangle(矩形类) 和派生类 Cube(正方体)
```cpp
#include <iostream>
using namespace std;
class CShape {
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
class CRectangle : public CShape {
public:
CRectangle(double l, double w) : length(l), width(w) {}
double area() override {
return length * width;
}
double perimeter() override {
return 2 * (length + width);
}
protected:
double length;
double width;
};
class CCuboid : public CRectangle {
public:
CCuboid(double l, double w, double h) : CRectangle(l, w), height(h) {}
double volume() {
return length * width * height;
}
private:
double height;
};
void Display(CRectangle& r) {
cout << "The area of the rectangle is " << r.area() << endl;
cout << "The perimeter of the rectangle is " << r.perimeter() << endl;
}
void Display(CCuboid& c) {
cout << "The area of the cuboid is " << c.area() << endl;
cout << "The perimeter of the cuboid is " << c.perimeter() << endl;
cout << "The volume of the cuboid is " << c.volume() << endl;
}
int main() {
CRectangle r(2, 3);
CCuboid c(2, 3, 4);
Display(r);
Display(c);
return 0;
}
```
阅读全文