2014-03-26 28 views
0

我想了解繼承中的鑽石問題,我正在模擬它。這是我有:爲什麼我不能將超類引用投射到擴展另一個超類的子類?

using namespace std; 

class top { 
    int a; 
}; 

class left : public top { 
    int b; 
}; 

class right : public top { 
    int c; 
}; 

class bottom : public left, public right { 
    int d; 
}; 

int main() { 

    bottom* b = new bottom(); 

    left* l = (left*) b; 
    right* r = (right*) b; 

    cout << l << " " << r << endl; 
    return 0; 
} 

我不應該能夠實現這一目標嗎?大多數教程都說這是可能的。不過,我收到編譯器錯誤,說它是模糊的。有人可以在這裏給出解釋和一些背景嗎?

回答

1

您應該避免using namespace stdstd::leftstd::right與您自己的定義衝突。

請參閱http://ideone.com/tMa28j的工作版本。

+0

謝謝。這解決了它。 – shrinidhisondur

+0

@shrinidhisondur不客氣。 –

相關問題