派生类构造函数和析构函数的执行顺序
链接: link.
#include <iostream>
using namespace std;
class Contained1 {
public:
Contained1() { cout << "Contained1 ctor\n"; }//构造constructor
~Contained1() {cout << "Contained1 dtor\n";}//析构destructor
};
class Contained2 {
public:
Contained2() { cout << "Contained2 ctor\n"; }
~Contained2() {cout << "Contained2 dtor\n";}
};
class Contained3 {
public:
Contained3() { cout << "Contained3 ctor\n"; }
~Contained3() {cout << "Contained3 dtor\n";}
};
class BaseContainer {
public:
BaseContainer() { cout << "BaseContainer ctor\n"; }
~BaseContainer() { cout << "BaseContainer dtor\n"; }
private:
Contained1 c1;
Contained2 c2;
};
class DerivedContainer : public BaseContainer {
public:
DerivedContainer() : BaseContainer() { cout << "DerivedContainer ctor\n"; }
~DerivedContainer();
private:
Contained3 c3;
};
DerivedContainer::~DerivedContainer() { cout << "DerivedContainer dtor\n"; }
int main() {
DerivedContainer dc;
}
执行结果如下:
Contained1 ctor
Contained2 ctor
BaseContainer ctor
Contained3 ctor
DerivedContainer ctor
DerivedContainer dtor
Contained3 dtor
BaseContainer dtor
Contained2 dtor
Contained1 dtor
上面的示例显示,在派生类的构造函数中,基类和成员构造函数的调用顺序。 首先,调用基构造函数,然后按照基类成员在类声明中出现的顺序对这些成员进行初始化,然后,调用派生构造函数。
析构函数的执行顺序与构造函数相反,可类比于穿衣服和脱衣服。