作者: 大呀大帝国 </br>
email:drnijq@126.com
刚刚遇到了这么一个例子:
#include <iostream>
using namespace std;
class T {
public:
T () {
cout << "T()" << endl;
}
~T () {
cout << "~T()" << endl;
}
};
class A {
public:
A () : _t () {
cout << "A()" << endl;
}
virtual ~A () {
cout << "~A()" << endl;
}
T _t;
};
class B : public A{
public:
B () {
cout << "B()" << endl;
}
virtual ~B () {
cout << "~B()" << endl;
}
};
int main(int argc, char const *argv[]) {
B b0;
return 0;
}
运行后的结果为
[root@b7cdfa01d097 host_dir]# ./a.out
T()
A()
B()
~B()
~A()
~T()
可以看出,首选构造函数会先调用基类的构造函数,所以顺序为 T() -> A () -> B()
构造函数正好反过来,先构造的后析构,所以顺序为 ~B() -> ~A() -> ~T()