思考这样一串代码的运行结果:
#include <iostream>
using namespace std;
class Person
{
public:
~Person() { cout << "~Person()" << endl; }
};
class Student:public Person
{
public:
~Student() { cout << "~Student()" << endl; }
};
int main()
{
Person p;
Student s;
return 0;
}
结果为:

甚至这样:

搜了不少的博客发现很少有把这样一个运行结果说清楚的,于是写一篇博客补充一下:
在我的往期文章C++入门11------详解C++继承(菱形继承与虚拟继承)中已经介绍了:
**构造时先父后子,析构时先子后父。**所以这里就不再详细说这个问题。
其实造成这样的运行结果原因也很简单,在我的往期文章C++入门5------C/C++动态内存管理(new与delete)中提过一嘴:局部变量是存放在栈区上的,而栈遵循先进先出,后进后出的原则:
在我们的代码中:
①p首先被定义,被压入栈中;
②然后s被定义,被压入栈中,位于p的上方;
③当main函数结束时,栈开始弹出对象进行销毁:
所以先弹出s再弹出p,又结合析构时先子后父的原则:
④Student是Person的派生类,所以s弹出时先调用~Student(),再调用~Person();
⑤p弹出时只调用~Person()。

