设计一个CShape基类,由CShape类派生出矩形类CRectangle。再由矩形类CRectangle派生出长方体类CCuboid,设计不属于这些类的Display函数,用来输出CRectangle和CCuboid对象的周长和面积。根据下面的测试程序设计这些
时间: 2024-05-15 08:18:06 浏览: 247
类:
```cpp
#include <iostream>
using namespace std;
class CShape {
public:
virtual double GetArea() {
return 0.0;
}
virtual double GetPerimeter() {
return 0.0;
}
};
class CRectangle : public CShape {
public:
CRectangle(double _width, double _height) : width(_width), height(_height) {}
virtual double GetArea() {
return width * height;
}
virtual double GetPerimeter() {
return 2 * (width + height);
}
private:
double width, height;
};
class CCuboid : public CRectangle {
public:
CCuboid(double _width, double _height, double _depth) : CRectangle(_width, _height), depth(_depth) {}
double GetVolume() {
return GetArea() * depth;
}
private:
double depth;
};
void Display(CShape* pShape) {
if (dynamic_cast<CRectangle*>(pShape)) {
cout << "Area: " << pShape->GetArea() << endl;
cout << "Perimeter: " << pShape->GetPerimeter() << endl;
} else if (dynamic_cast<CCuboid*>(pShape)) {
cout << "Area: " << pShape->GetArea() << endl;
cout << "Perimeter: " << pShape->GetPerimeter() << endl;
cout << "Volume: " << dynamic_cast<CCuboid*>(pShape)->GetVolume() << endl;
}
}
int main() {
CRectangle rect(2.0, 3.0);
CCuboid cuboid(2.0, 3.0, 4.0);
Display(&rect);
Display(&cuboid);
return 0;
}
```
这段代码实现了一个CShape基类以及由CShape类派生出矩形类CRectangle和长方体类CCuboid。在这个程序中我们设计了一个Display函数,用来输出CRectangle和CCuboid对象的周长、面积和体积。
阅读全文