多重继承的构造函数是否被多次调用? [英] Are multiple-inherited constructors called multiple times?
问题描述
多重继承的构造函数是否被多次调用?并以什么顺序调用构造函数?这是否取决于继承列表中的顺序?
这里是一个示例(仅用于说明情况,不是真实的示例).
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()
?
编写方式Derived
具有两个类型为Base
的不同子对象,每个子对象都有自己的构造函数,称为从相应的DerivedBaseXXX
构造函数中获取,它是其子对象.调用的顺序遵循声明的顺序.
相反,在声明DerivedBaseXXX : virtual public Base
时,只有一个 Base
子对象,并且其构造函数是从最派生的对象(即,从Derived
对象)调用的. /p>
(要更详细地说明:一个(可能是单继承)的类是通过以下步骤构造的:首先1)调用基类的构造函数,然后2)按照声明的顺序调用所有成员对象的构造函数,最后3)执行构造函数的函数体.这适用于递归,对于多重继承,您只需按照声明继承的顺序调用所有基类的构造函数,即可替换(1).只有虚拟继承才在这里增加了真正的复杂性.)
Are multiple-inherited constructors called multiple times? And in what order are constructors called? Does this depend on the order in the inheritance list?
Here is an example (it's only for making the situation clear, no real-life example).
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();
Is the Base()
constructor called twice? And in what order are the constructors called? Base first? Or DerivedBaseOne()
or DerivedBaseTwo()
first?
The way you write it, Derived
has two distinct subobjects of type Base
, and each gets their own constructor called from the respective DerivedBaseXXX
constructor of which it is the subobject. The order of calls follows the order of declaration.
By contrast, of you declare DerivedBaseXXX : virtual public Base
, then there is only one Base
subobject, and its constructor is called from the most derived object, i.e. from the Derived
object.
(To explain in a bit more detail: A (possibly singly-inheriting) class is constructed by first 1) calling the base class's constructor, then 2) calling the constructors of all member objects in their order of declaration, and finally 3) executing the constructor function body. This applies recursively, and for multiple inheritance, you just replace (1) by calling all the base class's constructors in the order in which the inheritance was declared. Only virtual inheritance adds a genuine extra layer of complication here.)
这篇关于多重继承的构造函数是否被多次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!