在以下代码中,使用Multi Path Inheritance
解析了Virtual Class
构造函数是如何工作的?
无法继承构造函数或虚拟或静态。
/*Multi Path Inheritance*/
class A{
public:
int a;
A(){
a=50;
}
};
class B:virtual public A{
public:
/*B(){
a = 40;
}*/
};
class C:virtual public A{
public:
/*C(){
a = 30;
}*/
};
class E:virtual public A{
public:
E(){
a = 40;
}
};
class D : public B, public C, public E{
public:
D(){
cout<<"The value of a is : "<<a<<endl;
}
};
int main(int argc, char *argv[]){
D d;
return 0;
}
答案 0 :(得分:2)
基于标准12.6.2 / 10的以下配额,因此将在以下orde中调用构造函数体:A-> B-&gt; C-&gt; D,因此a的最终值将为40。
在非委托构造函数中,初始化继续进行 以下顺序:
— First, and only for the constructor of the most derived class (1.8), 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. — 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).
答案 1 :(得分:1)