[英]C++ Multiple inheritance, virtual method override problems, and covariant return type
[英]C++ covariant return type error with multiple inheritance
我有與此相同的代碼:
class X {};
class Y {};
template< typename T>
class C {
public:
virtual T * foo() = 0;
};
class A : public C< X> {
public:
X * foo() {};
};
class B : public A {};
class D : public B, public C< Y> {
public:
Y * foo() {}; //this is the only one method I need here. Not A::foo!
};
我有這個錯誤:
error: invalid covariant return type for 'virtual Y* D::foo()'
Y * foo() {};
^
和:
error: overriding 'virtual X* A::foo()'
X * foo() {};
^
我相信我可以在B類或D 類中寫一些東西以防止A :: foo繼承,但我不知道是什么。 也許有一些功能可以在C ++中重命名沖突名稱?
PS>我不能使用C ++ 11,只能使用舊的C ++ 98。
TL; DR
在D
級覆蓋foo
。 由於不相關的X
和Y
返回類型, foo
方法無法協變。 兩者都不能因為不同的返回類型而重載,但簽名相同。
說明
讓我們將代碼清理為具有相同問題的較小代碼段:
class X {};
class Y {};
template<typename T>
class C {
public:
virtual T * foo() = 0;
};
class A : public C<X> {
public:
// Your code:
// X * foo() {}; <---- This method is irrelevant to the problem
// virtual X * foo() {};
// ^^^^^^^^^^^^^^^^^^^^^
// This method declared via inheritance and template
// and implicitly exists in this class, (look at keyword `virtual`)
};
class D : public A, public C<Y> {
public:
/*virtual*/ Y * foo() {}; // `virtual` comes from C<X>
};
好吧, D
類繼承了A
和C<Y>
兩個foo
方法。 這兩種導入的方法可以共存,因為它們來自不同的父母,可以通過合格的調用來調用,例如D d; dA::foo();
D d; dA::foo();
。
但是在這種情況下,當你嘗試在D
類中覆蓋foo
時,問題會出現在圖片中:
/*virtual*/ Y * foo() {};
在D
類中,有一個帶有簽名X * foo()
的方法,它繼承自A
,你重寫方法Y * foo()
。 這些不能協變, 因為Y
不是從X
派生的 。 另一方面,這個foo
不能重載另一個, 因為返回類型不是函數簽名的一部分 。
閱讀clang的錯誤信息很好:
錯誤:虛函數'foo'的返回類型與它覆蓋的函數的返回類型不一致('Y *'不是從'X *'派生的)
virtual Y * foo() {};
解
最好的解決方案是簡化您的設計並擺脫這些復雜的繼承,模板化和同名方法!
你說你不需要在C<X>
聲明並在A
實現的foo
方法,但由於你的D
類也是A
和C<X>
,客戶端可能依賴於這種方法可用,並返回一個X
C ++不支持刪除繼承的方法AFAIK,並且有充分的理由,因為這會違反Liskov替換原則。
如果你在這里刪除或隱藏了C<X>::foo
,那么在預期A
, B
或C<X>
的實例的情況下,不能使用D
的實例。 所以我擔心這里沒有解決這個問題的好辦法。 如果您只是嘗試在D
重用A
或B
中的實現,那么在這種情況下您可能應該考慮組合而不是繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.