c++ - 阶梯式 C++ 虚拟继承

标签 c++ multiple-inheritance virtual-inheritance

如果我有如下类继承关系

               a
              /  \
             b    c
              \   |
               |  d
                \/ \
                e   f
                 \ /
                  g

以下是正确的定义吗?

    class A {};
    class B: public virtual A {};
    class C: public virtual A {};
    class D: public C {};
    class E: public B, public virtual D  {};
    class F: public virtual D {};
    class G: public E, public F {};

我让 A 和 D 都是虚拟继承的,因为我假设每个 union 类都需要是虚拟的。

此外,我不确定 C++ 是如何定义上述情况的构造函数顺序的。链接 https://isocpp.org/wiki/faq/multiple-inheritance#mi-vi-ctor-order

The very first constructors to be executed are the virtual base classes anywhere in the hierarchy. They are executed in the order they appear in a depth-first left-to-right traversal of the graph of base classes, where left to right refer to the order of appearance of base class names.

After all virtual base class constructors are finished, the construction order is generally from base class to derived class. The details are easiest to understand if you imagine that the very first thing the compiler does in the derived class’s ctor is to make a hidden call to the ctors of its non-virtual base classes (hint: that’s the way many compilers actually do it). So if class D inherits multiply from B1 and B2, the constructor for B1 executes first, then the constructor for B2, then the constructor for D. This rule is applied recursively; for example, if B1 inherits from B1a and B1b, and B2 inherits from B2a and B2b, then the final order is B1a, B1b, B1, B2a, B2b, B2, D.

Note that the order B1 and then B2 (or B1a then B1b) is determined by the order that the base classes appear in the declaration of the class, not in the order that the initializer appears in the derived class’s initialization list.

如果有,顺序是怎样的?

  A, D, B, C, D, F, G

我不希望 D 在 C 之前构造。正确的构造函数顺序是什么?

最佳答案

构造G类的对象时,首先初始化虚基类。这导致 AD 的构造函数被调用。 D 的构造函数将构造它的基础 C 对象。然后将调用G 的非基类的构造函数,即EFE 的构造函数将调用B 的构造函数。这给出了最终顺序:

A C D B E F G

关于c++ - 阶梯式 C++ 虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49504316/

相关文章:

c++ - 如何访问窗口的内部位图?

python: 类 super() 的代理对象,在指定类开始 MRO 搜索

c# - 固有实现的接口(interface)

c++ - 继承顺序是怎样的

c++ - 删除后 async_write 会导致段错误吗?

c++ - 必须重写的虚函数

c++ - 方法问题: Deleting duplicate chars in an array

C++ 虚拟继承和构造函数

C++ 虚拟继承

c++ - 虚拟继承如何解决 "diamond"(多重继承)的歧义?