gpt4 book ai didi

c++ - 是否多次调用多个继承的构造函数?

转载 作者:IT老高 更新时间:2023-10-28 21:55:19 32 4
gpt4 key购买 nike

多重继承的构造函数会被多次调用吗?构造函数的调用顺序是什么?这是否取决于继承列表中的顺序?

这是一个例子(只是为了说明情况,没有现实生活中的例子)。

class Base {};
class DerivedBaseOne : public Base {};
class DerivedBaseTwo : public Base {};
class Derived : public DerivedBaseTwo, public DerivedBaseOne
{};

//somewhere in the code, is Base() called two times here?
Derived * foo = new Derived();

Base() 构造函数是否被调用了两次?构造函数的调用顺序是什么?先打基础?还是先 DerivedBaseOne()DerivedBaseTwo()

最佳答案

继承层次结构的构造函数调用顺序为:

Base()  
DerivedBaseTwo()
Base()
DerivedBaseOne()
Derived()

顺序确实定义明确,取决于您提到基类派生的顺序以及您在类中为成员声明成员的顺序。 (请参阅下面的 C++ 标准引用。)

Base() 构造函数会被调用两次吗?

Base() 类构造函数在这里被调用了两次,因为两个类 DerivedBaseTwo()DerivedBaseOne() 派生自它,所以基类构造函数为它们中的每一个调用一次。您的 Derived 类通过多个路径具有两个不同的 Base 子对象(一个通过 DerivedBaseOne() 另一个通过 DerivedBaseTwo())。

多重继承的类层次结构是不寻常的,它会导致一个称为 Diamond Shaped Inheritance Problem 的问题。为了避免这个问题,C++ 引入了 Virtual base class 的概念。


引用:

C++03 标准:12.6.2/5,初始化基和成员

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.

— 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).

— Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

— Finally, the body of the constructor is executed.

关于c++ - 是否多次调用多个继承的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7405839/

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