代码:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A constructor" << endl;
}
};
class C
{
public:
C() {
cout << "C constructor" << endl;
}
};
class B :public A
{
public:
B()
{
cout << "B constructor" << endl;
}
private:
C c;
};
int main()
{
B b;
}
环境: VS2022
输出:
A constructor
C constructor
B constructor
环境: g++ 11.1.0 (MANJARO)
输出:
A constructor
C constructor
B constructor
从这里可以看出,两个编译器在实现的时候,都是先调用基类的构造函数,再调用包含类的构造函数,最后调用自己的构造函数。