c++ - 构造函数的调用顺序

标签 c++ inheritance constructor multiple-inheritance

#include <iostream>
using namespace std;    
struct A{
  A() {cout << "A" << endl;}
  A(int a) {cout << "A+" << endl;}
};

struct B : virtual A{
  B() : A(1) {cout << "B" << endl;}
};
struct C : virtual A{
  C() : A(1) {cout << "C" << endl;}
};
struct D : virtual A{
  D() : A() {cout << "D" << endl;}
};
struct E : B, virtual C, D{
  E(){cout << "E" << endl;}
};
struct F : D, virtual C{
  F(){cout << "F" << endl;}
};
struct G : E, F{
  G() {cout << "G" << endl;}
};

int main(){
  G g;
  return 0;
}

程序打印:

A
C
B
D
E
D
F
G

我想知道应该使用什么规则来确定调用构造函数的顺序。谢谢。

最佳答案

您应该遵循 C++ 标准中给出的规则:

[C++11: 12.6.2/10]: In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.

[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]

关于c++ - 构造函数的调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21033845/

相关文章:

c++ - 引用这些指针时我是如何不小心覆盖的?

ios - 删除导航按钮

ruby - 在 Go 中建模 "superclass method implementation"的最佳方法是什么?

c++ - C++中的外部模板构造函数

C++ - 在类中调用与类同名的函数

c++ - 模板的成员 typedef 在 VS 而非 GCC 中用于参数未声明的标识符

c++ - 比较 operator== 中的对象指针

java - 为什么这个类有两个构造函数?

c++ - 如何在 C++ 中包含、加载和使用 .dll

java - 变量以某种方式失去了值(value)?