简体   繁体   English

C ++继承顺序以什么方式影响构造函数?

[英]In what ways does C++ inheritance order affect a constructor?

If I define a structure that inherits from multiple other structures, how does the order that I list them in affect something like this: 如果我定义了一个从多个其他结构继承的结构,那么列出它们的顺序将如何影响这样的事情:

struct D: C,B{
    D(): B(), C(){...}
};

Simple question, but thanks in advance! 简单的问题,但在此先感谢!

The order of construction depends on the sequence of inheritance. 构造顺序取决于继承顺序。 Initialization order doesn't matter. 初始化顺序无关紧要。 GCC actually issues warning in this case. 在这种情况下,GCC实际上会发出警告。

In constructor 'D::D()': 在构造函数'D :: D()'中:

main.cpp:16:17: warning: base 'B' will be initialized after [-Wreorder] main.cpp:16:17:警告:[-Wreorder]之后将初始化基数'B'

  D(): B(), C(){ ^ 

main.cpp:16:17: warning: base 'C' [-Wreorder] main.cpp:16:17:警告:基本'C'[-Wreorder]

main.cpp:16:5: warning: when initialized here [-Wreorder] main.cpp:16:5:警告:在此处初始化时[-Wreorder]

  D(): B(), C(){ 

It is clearly specified in the standard as well. 该标准中也明确规定了它。 From section 12.6.2 Initializing bases and members 从第12.6.2节开始,初始化基址和成员

Initialization shall proceed in the following order: 初始化应按以下顺序进行:

— First, and only for the constructor of the most derived class as described below, virtual base classes shall be 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 class names in the derived class base-specifier- list . —首先,并且仅对于如下所述的最大派生类的构造函数,虚拟基类应按照它们在基类的有向无环图的深度优先从左到右遍历时出现的顺序进行初始化,其中“ “从左到右”是基类名称在派生类base-specifier-list中的出现顺序。
— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers). —然后, 直接基类应按照它们出现在base-specifier-list中的声明顺序进行初始化(与mem-initializers的顺序无关)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM