-1

我需要知道在派生类构造函数的调用中何时调用基类的构造函数。

Small example:

class Base1
{...}

class Base2
{...}

class Derived : Base1,Base2
{...}

int main (int argc, char** argv)
{
Derived Child;
}

使用该命令调用Derived Child;构造函数Derived,但我读过在Derived执行类构造函数之前执行所有基本构造函数,即 Base1 和 Base2 的构造函数。

所以我想知道如果类的构造函数Derived看起来像这样,事件顺序将如何

Derived::Derived (Parameters)
:                      //initialization list
Base2 (Parameters)
{...}

类的构造函数是Base2现在在构造函数的初始化列表中Derived调用还是之前调用。此外,所有基类构造函数都是在构造函数调用开始时Derived或类构造函数初始化列表Derived开始时调用的。

直接问候

4

1 回答 1

1

构造函数的调用顺序是第一个基类,然后是派生类。

在当前示例中,构造函数的调用顺序为:Basis1 Basis2 Derived

如果我们将类定义更改为

派生类:Basis2,Basis1

那么构造函数调用的顺序将是:Basis2 Basis1 Derived

基类构造函数总是在派生类之前调用​​,无论是否从初始化列表中显式调用。

于 2013-11-26T11:05:54.387 回答