调用顺序.cpp
#include <iostream>
class A
{
public:
A()
{
std::cout << "A" ;
}
};
class B: public A
{
public:
B()
{
std::cout << "B" ;
}
};
class C: virtual public A
{
public:
C()
{
std::cout << "C" ;
}
};
class D: public B, public C
{
public:
D()
{
std::cout << "D" ;
}
};
int main()
{
D d;
return 0;
}
编译
g++ order-of-call.cpp -std=c++11
输出
AABCD
为什么两个 A
一起输出?。我期待像 ABACD
这样的东西。但是如果我这样改变继承顺序
class D: public C, public B
,输出符合预期ACABD
。顺序是标准的一部分还是特定于 g++。
最佳答案
这是有道理的,因为虚拟基类是在非虚拟基类之前构造的。所以在你的情况下它是:virtual A
,non-virtual A
,BCD
。如果更改继承顺序,则为 virtual A
、C
、non-virtual A
、BD
。检查这个:https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr389.htm
初始化类的顺序如下:
- Constructors of Virtual base classes are executed, in the order that they appear in the base list.
- Constructors of nonvirtual base classes are executed, in the declaration order.
- Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
- The body of the constructor is executed.
关于c++ - 关于构造函数调用顺序和虚基类的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722389/