gpt4 book ai didi

c++ - 虚继承中构造函数的调用顺序是怎样的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:36 27 4
gpt4 key购买 nike

c++虚继承中构造函数的调用顺序是怎样的?

针对下面两种多重继承的情况;

(I) 对于下面的代码,没有虚继承;

class a
{
public:

a()
{
cout<<"\t a";
}

};

class b: public a
{
public:
b()
{
cout<<"\t b";
}

};

class c: public b
{
public:

c()
{
cout<<"\t c";
}

};

class d: public c
{
public:

d()
{
cout<<"\t d";
}
};

class e: public c, public d
{
public:

e()
{
cout<<"\t e";
}
};

class f: public b, public e
{
public:

f()
{
cout<<"\t f";
}
};


int main()
{

f aaa;

return 0;
}

输出是:

     a       b       a       b       c       a       b       c       d       e       f

(II)类e虚继承:

class a
{
public:

a()
{
cout<<"\t a";
}

};

class b: public a
{
public:
b()
{
cout<<"\t b";
}

};

class c: public b
{
public:

c()
{
cout<<"\t c";
}

};

class d: public c
{
public:

d()
{
cout<<"\t d";
}
};

class e: public c, public d
{
public:

e()
{
cout<<"\t e";
}
};

class f: public b, public virtual e
{
public:

f()
{
cout<<"\t f";
}
};


int main()
{

f aaa;

return 0;
}

输出是:

     a       b       c       a       b       c       d       e       a       b       f

谁能解释一下这两种情况下的输出是如何获得的?虚继承如何影响对象的构造?

最佳答案

首先初始化虚基类,否则直接基类按照基类声明从左到右的顺序初始化。

对于类fclass f: public b, public e,没有虚基类,直接基类b会是首先初始化,然后是e。 (从左到右的顺序)

对于class f: public b, public virtual e,首先会初始化虚基类e,然后是b

参见 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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com