声明一个基类Shape(形状),其中包含一个方法来计算面积; 从Shape 派生两个类:Rectangle(矩形类)和Circle(圆形类); 从Rectangle 类派生正方形类Square; 分别实现派生类构造函数、析构函数及其它功能的成员函数; 创建各派生类的对象,观察构造函数、析构函数的调用次序; 计算不同对象的面积。
时间: 2023-08-15 11:05:52 浏览: 47
好的,这是一个比较典型的面向对象的继承问题,我可以帮你解答。
首先,我们需要声明 Shape 基类,其中包含一个计算面积的方法:
```c++
class Shape {
public:
virtual double area() const = 0; // 声明一个纯虚函数,子类必须实现
};
```
然后我们从 Shape 派生出 Rectangle 和 Circle 两个类,并实现它们各自的 area() 方法:
```c++
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
virtual double area() const {
return width * height;
}
private:
double width, height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
virtual double area() const {
return 3.1415926 * radius * radius;
}
private:
double radius;
};
```
接下来,我们从 Rectangle 派生出 Square 类,同样实现它的 area() 方法:
```c++
class Square : public Rectangle {
public:
Square(double side) : Rectangle(side, side) {}
};
```
这里我们直接从 Rectangle 派生,因为正方形也是一种矩形,只不过边长相等。
最后,我们可以创建各个类的对象,并调用它们的 area() 方法:
```c++
int main() {
Rectangle r(3, 4);
Circle c(2);
Square s(5);
cout << "Rectangle area: " << r.area() << endl;
cout << "Circle area: " << c.area() << endl;
cout << "Square area: " << s.area() << endl;
return 0;
}
```
输出结果为:
```
Rectangle area: 12
Circle area: 12.5664
Square area: 25
```
我们可以看到,不同对象的面积被正确计算了。至于构造函数和析构函数的调用次序,这个取决于具体的实现,但一般来说,先调用基类的构造函数,然后调用派生类的构造函数;析构的顺序则相反,先调用派生类的析构函数,再调用基类的析构函数。