构造函数调用顺序是从最基类开始到派生类结束,析构函数则是相反的。
#include <iostream>
using namespace std;
class Base1{
public:
Base1(){
cout<<"Base1"<<endl;
}
~Base1(){
cout<<"~Base1"<<endl;
}
};
class Base2: public Base1{
public:
Base2(){
cout<<"Base2"<<endl;
}
~Base2(){
cout<<"~Base2"<<endl;
}
};
class Derived: public Base2{
public:
Derived(){
cout<<"Derived"<<endl;
}
~Derived(){
cout<<"~Derived"<<endl;
}
};
int main() {
Base1 b1;
Base2 b2;
Derived d1;
return 0;
}
输出如下:构造函数确实是从最基类(最鸡肋哈哈)开始一直调用它的构造函数到该派生类的构造函数为止。