设计一个程序声明一个基类Shape(形状),其中包含一个方法来计算面积; 从Shape 派生两个类:Rectangle(矩形类)和Circle(圆形类); 从Rectangle 类派生正方形类Square; 分别实现派生类构造函数、析构函数及其它功能的成员函数; 创建各派生类的对象,观察构造函数、析构函数的调用次序; 计算不同对象的面积。
时间: 2023-08-15 21:04:54 浏览: 60
好的,这是一个经典的面向对象编程问题。下面是一个可能的解决方案:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double getArea() { return 0; }
};
class Rectangle : public Shape {
public:
Rectangle(double _width, double _height) : width(_width), height(_height) {
cout << "Constructing a rectangle..." << endl;
}
~Rectangle() {
cout << "Destructing a rectangle..." << endl;
}
double getArea() override { return width * height; }
private:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double _radius) : radius(_radius) {
cout << "Constructing a circle..." << endl;
}
~Circle() {
cout << "Destructing a circle..." << endl;
}
double getArea() override { return M_PI * radius * radius; }
private:
double radius;
};
class Square : public Rectangle {
public:
Square(double _side) : Rectangle(_side, _side) {
cout << "Constructing a square..." << endl;
}
~Square() {
cout << "Destructing a square..." << endl;
}
};
int main() {
Shape* shape1 = new Rectangle(3, 4);
Shape* shape2 = new Circle(2);
Shape* shape3 = new Square(2);
cout << "Shape 1 area: " << shape1->getArea() << endl;
cout << "Shape 2 area: " << shape2->getArea() << endl;
cout << "Shape 3 area: " << shape3->getArea() << endl;
delete shape1;
delete shape2;
delete shape3;
return 0;
}
```
这个程序定义了一个基类 `Shape`,包含了一个虚函数 `getArea()` 用于计算面积。然后从 `Shape` 派生了两个类 `Rectangle` 和 `Circle`,分别表示矩形和圆形。这两个派生类都重写了 `getArea()` 函数,用于计算自己的面积。
另外,从 `Rectangle` 派生了正方形类 `Square`。由于正方形可以看做是一种特殊的矩形,因此 `Square` 类只需要调用 `Rectangle` 的构造函数即可。
在 `main()` 函数中,我们分别创建了一个矩形、一个圆形、一个正方形的对象,并分别计算了它们的面积。然后再释放这些对象(调用 `delete`),观察析构函数的调用次序。
运行这个程序,可以得到如下输出:
```
Constructing a rectangle...
Constructing a circle...
Constructing a rectangle...
Constructing a square...
Shape 1 area: 12
Shape 2 area: 12.5664
Shape 3 area: 4
Destructing a rectangle...
Destructing a circle...
Destructing a square...
Destructing a rectangle...
```
可以看到,构造函数和析构函数的调用次序是符合预期的:先构造基类,再构造派生类;先析构派生类,再析构基类。同时,我们也成功地计算了不同图形的面积。
希望这个例子能够帮助你理解面向对象编程的基本思想和实现方式。