c++ - 在多级继承的情况下无法理解虚拟基类构造函数

标签 c++ constructor multiple-inheritance virtual-inheritance

在下面的程序中,如果我更改派生类“D”中的顺序,那么我将获得基类构造函数的不同顺序。

    #include <iostream>

    using namespace std;

    class A {
      public :
            A ()
            {
                cout << "A()" <<endl;
            }
    };

    class B : virtual A{
      public :
            B ()
            {
                cout << "B()" << endl;
            }
    };

    class C : virtual B{
      public :
            C ()
            {
                cout << "C()" << endl;
            }
    };

Case (1)
========
    class D : public A, public B, public C
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT : 
A()
B()
A()
B()
C()

Case (2)
========
    class D : public C, public B, public A
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT :
A()
B()
C()
B()
A()

Case (3)
========
    class D : public B, public A, public C
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT :
A()
B()
B()
A()
C()

谁能告诉我在虚拟类概念的情况下如何调用构造函数。

最佳答案

Please can anyone tell how constructors are called in case of virtual class concepts.

根据initialization order ,首先会初始化虚基类。

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)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

在这 3 种情况下,D 类继承自 ABC,有是 D 中的两个虚拟基类,即 A 通过 BC 继承,以及 B 通过 C 继承。而 A 将首先被初始化,因为它是最基类,所以对于所有 3 种情况, A()B() 将被打印一开始就出来了。

之后,直接基类将按从左到右的顺序进行初始化。对于第一种情况,它们将是 A() B() C(),对于第二种情况,它们将是 B() C() A(),对于第三种情况,它们将是 B() A () C().

关于c++ - 在多级继承的情况下无法理解虚拟基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38473155/

相关文章:

c++ - 当我创建一个 int 指针并实例化一个数组时,该数组在内存中发生了什么?

android - 有多个好的构造函数,Room 会选择无参数构造函数。如何解决此警告

具有常量构造函数参数的 C++ 变量构造函数方法

python - 如何处理多个不合作的 API 类并使它们合作?

ruby-on-rails - 在 Controller 之间共享一些 before_filters

c++ - C++中接口(interface)的实现

c++ - 浏览器帮助对象 UI

C++ 编译器函数调用

不为右值引用调用 C++ move 构造函数

c++ - shared_ptr<T>&& 作为构造函数参数的目的