类继承中构造函数、析构函数的执行顺序

测试代码:

#include<iostream>
using namespace std;

class base{
public:
 base(){cout<<"base created"<<endl;}
 ~base(){cout<<"base deleted"<<endl;}
};

class derive:public base{
public:
 derive(){cout<<"derive created/n";}
 ~derive(){cout<<"derive deleted/n";}
};

int main()
{
 derive cl;
 return 0;
}

 

测试结果:
base created
derive created
derive deleted
base deleted
请按任意键继续. . .

 

可见,类的继承中,首先执行的是积累的构造函数,然后才是派生类的构造函数。析构函数的顺序正好与构造函数的顺序相反。

你可能感兴趣的:(类继承中构造函数、析构函数的执行顺序)