0

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

2 回答 2

2

基于标准 12.6.2/10 的以下配额,因此构造函数主体将按以下顺序调用:A->B->C->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). 
于 2013-07-23T08:46:23.357 回答
1

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

至于构造函数,构造函数会在您指定它们时被调用。如果您不指定调用虚拟基类构造函数,

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

(在这里阅读)。

于 2013-07-23T07:50:03.827 回答