在下面的程序中,如果我更改派生类“D”中的顺序,那么我将获得基类构造函数的不同顺序。
#include <iostream>
using namespace std;
class A {
public :
A ()
{
cout << "A()" <<endl;
}
};
class B : virtual A{
public :
B ()
{
cout << "B()" << endl;
}
};
class C : virtual B{
public :
C ()
{
cout << "C()" << endl;
}
};
Case (1)
========
class D : public A, public B, public C
{
};
int main()
{
D d;
return 0;
}
OUTPUT :
A()
B()
A()
B()
C()
Case (2)
========
class D : public C, public B, public A
{
};
int main()
{
D d;
return 0;
}
OUTPUT :
A()
B()
C()
B()
A()
Case (3)
========
class D : public B, public A, public C
{
};
int main()
{
D d;
return 0;
}
OUTPUT :
A()
B()
B()
A()
C()
谁能告诉我在虚拟类概念的情况下如何调用构造函数。
最佳答案
Please can anyone tell how constructors are called in case of virtual class concepts.
根据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
在这 3 种情况下,D
类继承自 A
、B
和 C
,有是 D
中的两个虚拟基类,即 A
通过 B
和 C
继承,以及 B
通过 C
继承。而 A
将首先被初始化,因为它是最基类,所以对于所有 3 种情况, A()
和 B()
将被打印一开始就出来了。
之后,直接基类将按从左到右的顺序进行初始化。对于第一种情况,它们将是 A()
B()
C()
,对于第二种情况,它们将是 B()
C()
A()
,对于第三种情况,它们将是 B()
A ()
C()
.
关于c++ - 在多级继承的情况下无法理解虚拟基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38473155/