简体   繁体   English

为什么首先在C ++中初始化成员类?

[英]Why are member classes initialized first in C++?

I have tried the ff. 我已经尝试过了。 code: 码:

#include <iostream>
struct A
{
    A() { std::cout << "1"; }
    A(const A&) { std::cout << "2"; }
    A(A&&) { std::cout << "3"; }
};

struct B
{
    B() { std::cout << "4"; }
    B(const B& b) : a(b.a) { std::cout << "5"; }
    B(B&& b) : a(b.a) { std::cout << "6"; }
    A a;
};

int main()
{
    B b1;
    std::cout << "END OF b1" << std::endl;
    B b2 = std::move(b1);
}

And the output is: 输出为:

14END OF b1
26

I was just wondering why that is the behavior, how come the constructor of B is called second? 我只是想知道为什么会这样,为什么B的构造函数被称为第二个? I've also tried to use class instead of struct and it's the same behavior. 我也尝试过使用类而不是struct,这是相同的行为。

This is expected behavior. 这是预期的行为。 The initialization order is specified as 初始化顺序指定为

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists) 1)如果构造函数用于派生最多的类,则将虚拟基类按照它们在基类声明的深度优先从左到右遍历时出现的顺序进行初始化(从左到右是指外观在基本说明符列表中)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list 2)然后,直接基类按从左到右的顺序初始化,因为它们出现在该类的基符列表中

3) Then, non-static data members are initialized in order of declaration in the class definition. 3)然后,按类定义中的声明顺序初始化非静态数据成员。

4) Finally, the body of the constructor is executed 4)最后,执行构造函数的主体

Then the data member a is always initialized (step #3) before the execution of the constructor of B (step #4). 然后,在执行B的构造函数之前,始终将数据成员a初始化(步骤#3)(步骤#4)。

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

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