簡體   English   中英

具有多重繼承的C ++協變返回類型錯誤

[英]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() {};
     ^

http://ideone.com/PAgTdX

我相信我可以在B類D 類中寫一些東西以防止A :: foo繼承,但我不知道是什么。 也許有一些功能可以在C ++中重命名沖突名稱?

PS>我不能使用C ++ 11,只能使用舊的C ++ 98。

TL; DR

D級覆蓋foo 由於不相關的XY返回類型, 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類繼承了AC<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類也是AC<X> ,客戶端可能依賴於這種方法可用,並返回一個X C ++不支持刪除繼承的方法AFAIK,並且有充分的理由,因為這會違反Liskov替換原則。

如果你在這里刪除或隱藏了C<X>::foo ,那么在預期ABC<X>的實例的情況下,不能使用D的實例。 所以我擔心這里沒有解決這個問題的好辦法。 如果您只是嘗試在D重用AB中的實現,那么在這種情況下您可能應該考慮組合而不是繼承。

你可以使用私有繼承 A.

class B : private A {};

通常,返回類型不能是重載的唯一區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM