设计一个CShape基类,由CShape类派生出矩形类CRectangle。再由矩形类CRectangle派生出长方体类CCuboid,设计不属于这些类的Display函数,用来输出CRectangle和CCuboid对象的周长和面积。根据下面的测试程序设计这些
时间: 2024-05-08 09:20:04 浏览: 19
类:
```c++
class CShape {
public:
virtual double getArea() = 0; // 获取面积
virtual double getPerimeter() = 0; // 获取周长
};
class CRectangle : public CShape {
public:
CRectangle(double w, double h) : width(w), height(h) {}
double getArea() { return width * height; }
double getPerimeter() { return 2 * (width + height); }
protected:
double width, height;
};
class CCuboid : public CRectangle {
public:
CCuboid(double w, double h, double l) : CRectangle(w, h), length(l) {}
double getArea() { return 2 * (width * height + height * length + length * width); }
double getPerimeter() { return 2 * (width + height + length); }
private:
double length;
};
void display(CShape *shape) {
cout << "Area: " << shape->getArea() << endl;
cout << "Perimeter: " << shape->getPerimeter() << endl;
}
```
测试程序如下:
```c++
int main() {
CRectangle rect(3, 4);
CCuboid cuboid(3, 4, 5);
display(&rect);
display(&cuboid);
return 0;
}
```
测试结果:
```
Area: 12
Perimeter: 14
Area: 94
Perimeter: 22
```