构造函数调用在多重继承中的顺序 [英] Sequence of constructor calls in multiple inheritance

查看:194
本文介绍了构造函数调用在多重继承中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到很多,如果只有一个类在多重继承中被虚拟化
在这种情况下,构造函数调用的行为对我来说不清楚。
让例如代码 -

I have tried to find a lot that what if only one class is made virtual in multiple inheritance? The behaviour of constructor call is not clear to me in this case. Let say for example code-

#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

但在上面的代码中,如果我们更改

but in above code if we change this

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构造函数是不是在祖父后调用?

My concern is why parent1 constructor is not called after grandfather?

推荐答案

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

The standard says [C++11 section 12.6.2/10] that :


在非委托构造函数中,初始化在
中按顺序进行:

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

并且只对最派生类的构造函数,
虚拟基类按照它们出现在
深度上的顺序初始化 - 首先从左到右遍历
的有向无环图基类,其中从左到右是派生类base-specifier-list中
基类的出现顺序。

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

然后,直接基类以声明顺序初始化为
,它们出现在base-specifier-list中(不管
mem-initializers的顺序如何)。

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

- 然后,非静态数据成员按照在类定义中声明的
的顺序进行初始化(同样不考虑
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.

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

So your virtual base classes are always built first... This is really important in the case of virtual base class sharing.

这篇关于构造函数调用在多重继承中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆