c++ - 多重继承中的构造函数调用顺序

标签 c++ oop constructor multiple-inheritance

我试图找到很多如果在多重继承中只有一个类是虚拟的怎么办? 在这种情况下,我不清楚构造函数调用的行为。 比方说代码-

#include<iostream>
using namespace std;
class grand{
public:
    grand(){cout<<"grandfather"<<endl;}
};
class parent1:virtual public grand{   //virtual used only here
public:
    parent1(){cout<<"parent1 "<<endl;}
};
class parent2: public  grand{
public:
    parent2(){cout<<"parent2"<<endl;}
};
class child:public parent1,public parent2{
public:
    child(){cout<<"child"<<endl;}
};
int main()  {
    child s;
    return 0;
}

这段代码的输出是

grandfather
parent1 
grandfather
parent2
child

但是在上面的代码中如果我们改变这个

class parent1:virtual public grand{
public:
    parent1(){cout<<"parent1 "<<endl;}
};
class parent2: public  grand{
public:
    parent2(){cout<<"parent2"<<endl;}
};

为此

class parent1:public grand{   //virtual removed from here
public:
    parent1(){cout<<"parent1 "<<endl;}
};
class parent2:virtual public  grand{  //virtual is added here
public:
    parent2(){cout<<"parent2"<<endl;}
};

输出显示为

grandfather
grandfather    //why parent1 constructor is not called here?
parent1 
parent2
child

我担心的是为什么在祖父之后没有调用 parent1 构造函数?

最佳答案

标准说 [C++11 第 12.6.2/10 节]:

In a non-delegating constructor, initialization proceeds in the following order:

— First, and only for the constructor of the most derived class, virtual base classes are 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 classes in the derived class base-specifier-list.

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

— Finally, the compound-statement of the constructor body is executed.

所以你的虚拟基类总是首先构建...这在虚拟基类共享的情况下非常重要。

关于c++ - 多重继承中的构造函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457101/

相关文章:

c++ - 表达式不能作为函数使用,c++机器码函数

javascript - 带有构造函数的模块模式

c++ - 如何实现嵌套流畅的接口(interface)?

delphi - 隐藏无参数创建并重新引入?

java - 当构造函数具有类的类型时,这意味着什么?

java - 从构造函数调用方法

c++ - mt19937 和 uniform_real_distribution

c++ - Windows CredentialProvider 通过事件自动登录仍然显示登录按钮

c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题

c# - 从子元素引用父元素的值