多路径继承和

Multipath Inheritance and

本文关键字:继承 多路径      更新时间:2023-10-16

在以下代码中,使用Virtual Class解析Multi Path Inheritance建造师是如何工作的?构造函数不能是继承的、虚拟的或静态的。

/*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;
}

基于标准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). 

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

至于构造函数,构造函数在指定时被调用。如果您没有指定对虚拟基类构造函数的调用

类中任意位置的虚拟基类的构造函数继承层次结构由"最派生"类的构造函数。

(请在此处阅读)。