gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:30 25 4
gpt4 key购买 nike

调用顺序.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com