繁体   English   中英

多路径继承和

[英]Multipath Inheritance and

在以下代码中,使用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上,多么奇怪:))

对于构造函数,在指定构造函数时会对其进行调用。 如果您不指定对virtua基类构造函数的调用,

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

在这里阅读)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM