2013-07-23 52 views
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; 
} 
+0

的http://stackoverflow.com/questions/419943/virtual-inheritance – nouney

+1

可能重複的所有構造函數的調用開始基礎類到莫stvivived。的 –

+0

可能重複的[在C++中,什麼是一個虛基類?](http://stackoverflow.com/questions/21558/in-c-what-is-a-virtual-base-class) – RiaD

回答

1

你可以找到一個關於虛擬繼承here(是的,它實際上是在MSDN上,多麼奇怪:))

至於構造器,如您指定它們的構造函數被調用很多信息和例子。如果不指定虛基類的類的 繼承層次的任何地方一電一VIRTUA基類的構造函數,

構造是由「最派生」類的構造函數 叫。

(閱讀它here)。

2

基礎上從以下標準12.6.2/10配額,所以在構造體將在以下奧德被稱爲:A-> B-> C-> d,那麼最後一個值將是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).