声明一个基类Shape,在此基础上派生Rectangle和Circle,二者都有GetArea(),Retangle类派生了Square类,也有GetArea()函数计算对象的面积,编写程序测试。注意同名隐藏和类型兼容两种规则的体现,实现机制,可以使用派生类的对象调用同名函数,使用基类指针调用同名函数。
时间: 2024-02-21 21:02:19 浏览: 24
好的,这是一个经典的面向对象程序设计例子,我们可以按照以下方式实现:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double GetArea() { return 0.0; }
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
virtual double GetArea() { return width * height; }
protected:
double width, height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
virtual double GetArea() { return 3.14 * radius * radius; }
protected:
double radius;
};
class Square : public Rectangle {
public:
Square(double l) : Rectangle(l, l) {}
};
int main() {
Rectangle rect(3, 4);
Circle circle(5);
Square square(2);
Shape* pShape;
pShape = ▭
cout << "Rectangle area: " << pShape->GetArea() << endl;
pShape = &circle;
cout << "Circle area: " << pShape->GetArea() << endl;
pShape = □
cout << "Square area: " << pShape->GetArea() << endl;
Rectangle* pRect;
pRect = □
cout << "Square as Rectangle area: " << pRect->GetArea() << endl;
return 0;
}
```
输出结果如下:
```
Rectangle area: 12
Circle area: 78.5
Square area: 4
Square as Rectangle area: 4
```
在上面的程序中,我们定义了一个基类 Shape,并在其上面派生了 Rectangle 和 Circle 两个类。其中,基类 Shape 中定义了虚函数 GetArea(),以便用于多态调用。Rectangle 和 Circle 类分别实现了 GetArea() 函数,分别表示矩形和圆形的面积计算方法。
接着,我们又定义了一个 Square 类,它是 Rectangle 类的派生类,但是只有一个边长属性,因此我们在构造函数中将宽和高都设置为了这个边长。这样,我们就可以在 Square 类中重用 Rectangle 类的 GetArea() 函数,计算正方形的面积。
最后,在 main() 函数中,我们分别创建了 Rectangle、Circle 和 Square 三个对象,并使用一个基类指针 pShape 指向它们,通过多态调用各自的 GetArea() 函数。我们还创建了一个 Rectangle 指针 pRect,将其指向 Square 对象,以便测试类型兼容性。