多路径继承和

时间:2013-07-23 07:46:02

标签: c++ visual-c++

在以下代码中,使用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;
}

2 个答案:

答案 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)

你可以找到很多关于虚拟继承的信息和例子here(是的,它实际上是在msdn上,有多奇怪:))

对于构造函数,构造函数在您指定它们时被调用。如果没有为virtua-base类构造函数指定调用,

  

类中任何位置的虚拟基类的构造函数   继承层次结构由“最派生”类调用   构造

(请阅读here)。