2013-02-27 42 views
0

假設我們有Casating從派生基地,ambiguouty

class Base 
{ 
public: 
    virtual void foo(){} 
}; 

class Derived: public virtual Base 
{}; 

class Derived_Left: public Derived 
{}; 

class Derived_Right: public Derived 
{}; 

class Bottom: public Derived_Left, public Derived_Right 
{}; 

//讓討論案件

//情況1:

void foo() 
{ 
    Base *bptr = new Bottom; 
    Derived *dPtr = dynamic_cast<Derived*>(bptr);//dptr == 0 
} 

//案例2:

void goo() 
{ 
    Bottom *bptr = new Bottom; 
    Derived *ddtr = dynamic_cast<Derived*>(bptr); // ERROR 
} 

//main.cpp:在函數'void goo()'中:

//main.cpp:36:49:錯誤: '衍生' 是一個模糊基地 '底'

int main() 
{ 
} 

那麼,爲什麼代碼的

Base* bptr = new Bottom; 

的情況下進行編譯而不是在

Bottom* bptr = new Bottom; 
+0

首先我想提一下,我第一次在ubuntu g ++下編譯它。它給了我那個錯誤。但在家裏,我試圖在windows/visual stuio 2012下編譯它,它給了我一個警告警告C4540:dynamic_cast用於轉換爲無法訪問或模糊的基礎;運行時測試將失敗('Bottom *'到'Derived *') – 2013-02-28 04:40:06

回答

0

你已經問過同樣的問題。所以我會回答: 這是鑽石問題。 在這種情況下,您將類型爲Base的指針轉換爲派生的,Base類只知道在這種情況下唯一的子類。 但是從Bottom類型的對象來看,它不明確,您想要使用派生類的父類Derived_left或Derived_Right。