我有以下的鑽石類結構無法編譯:C++解決菱形繼承如果沒有虛擬繼承
class Base{
int a;
public:
virtual void doSomething();
};
class NotMineToTouch : public Base {};
class MyParentClass : public Base {};
class EvilDiamond : public NotMineToTouch, public MyParentClass {};
// I need these methods (that I cannot necessarily edit) to work for an EvilDiamond
void processBase (Base* b) { b->doSomething; /*...*/} // Cannot edit
void processParent (MyParentClass* p) { p->doSomething; /*...*/} // Can edit
void processNotMine (NotMineToTouch* n) { n->doSomething; /*...*/} // Cannot edit
我知道正常的解決方案是從Base
幾乎繼承;但是,我不允許更改NotMineToTouch
(或Base
)。還有其他解決方案嗎?我可以隨意改變MyParentClass
和EvilDiamond
;然而,EvilDiamond
必須從MyParentClass
和NotMineToTouch
繼承,而MyParentClass
必須從Base
繼承,並且不得從EvilDiamond
繼承。
我只得到一個警告並不是一個錯誤。你能否給我們提供你得到的實際編譯器錯誤,或者發佈代碼來重現問題。順便說一句,如果你不使用虛擬繼承,它不是鑽石。虛擬繼承是將兩個基礎合併爲一個創建鑽石形狀的基礎,如果您在圖表中繪製該基礎。 – Eelke
我們在Bases和MyParentClass的其他地方調用了虛方法getA()(在代碼中我不總是被允許改變)。它可能不是鑽石繼承,但它肯定是鑽石問題(請參閱標籤上的說明)。我在EvilDiamond上調用getA()時發生編譯器錯誤: 錯誤:成員'getA'的請求不明確 注:候選者爲:virtual int Base :: getA() note:virtual int Base :: getA() –
Can當你傳遞對象時,你沒有轉換到正確的類型? –