构造函数的调用顺序:
- 父类中对象成员的构造函数,按照它们在类中声明的顺序;
- 父类的构造函数,按照继承时声明的顺序(从左到右);
- 子类中对象成员的构造函数,按照它们在类中声明的顺序;
- 子类的构造函数
析构函数的调用顺序:与构造函数的调用顺序相反。
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; }
};
class B
{
public:
B() { cout << "B::B()" << endl; }
~B() { cout << "B::~B()" << endl; }
};
class C
{
private:
A a;
B b;
public:
C() { cout << "C::C()" << endl; }
~C() { cout << "C::~C()" << endl; }
};
class D : public C
{
private:
B b;
A a;
public:
D() { cout << "D::D()" << endl; }
~D() { cout << "D::~D()" << endl; }
};
int main()
{
D d;
return 0;
}
输出结果如下: