c++ - 关于构造函数调用顺序和虚基类的混淆

标签 c++ c++11

调用顺序.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 Anon-virtual ABCD。如果更改继承顺序,则为 virtual ACnon-virtual ABD。检查这个:https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr389.htm

初始化类的顺序如下:

  1. Constructors of Virtual base classes are executed, in the order that they appear in the base list.
  2. Constructors of nonvirtual base classes are executed, in the declaration order.
  3. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
  4. The body of the constructor is executed.

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

相关文章:

c++ - PkgConfig 模块 : INCLUDE_DIRS not listing all directories

c++ - 英特尔 AVX : 256-bits version of dot product for double precision floating point variables

c++ - *(&a)=5 是什么意思?

c++ - 将 fork() 与 boost::asio::ip::tcp::iostream 一起使用是否安全?

c++ - C++中静态方法局部变量的范围

c++ - 是否应该在 Windows DLL 库中导出析构函数?

c++ - C++中的无符号 double ?

c++11 - Android NDK 链接器错误:错误:未定义对 std::basic_string 的引用

c++ - boost::transform_iterator 不适用于 std::bind( &Pair::first, _1 )?

c++ - cout 同步关闭时的速度