[英]Compilation error when using multiple inheritance
無法編譯我的程序。 由於歷史原因,我的應用程序中的類層次結構有點“復雜”。 現在我面臨另一個問題:由於這種層次結構,它不會編譯。 我的項目太大,無法在此處顯示,但您可以在下面看到演示問題的示例。 有沒有一種簡單而優雅的方法來解決它? 每個接口/類都有大量的方法。 提前致謝。
struct ITest
{
virtual ~ITest() {}
virtual void a() = 0;
// and many other methods
};
struct Test1 : public ITest
{
virtual ~Test1() {}
virtual void a() override {}
// and many other methods overrides from ITest
// plus a lot of other logic
};
struct ExtendedTest1 : public Test1
{
virtual ~ExtendedTest1() {}
// a lot of some other stuff
};
struct ITest2 : public ITest
{
virtual ~ITest2(){}
// and big count of the its methods and logic
};
struct MainClass : public ExtendedTest1, public ITest2
{
virtual ~MainClass(){}
// a lot of logic
};
int main()
{
MainClass mainClassObj;
return 0;
}
和錯誤:
main.cpp: In function ‘int main()’:
main.cpp:36:15: error: cannot declare variable ‘mainClassObj’ to be of abstract type ‘MainClass’
MainClass mainClassObj;
^~~~~~~~~~~~
main.cpp:28:8: note: because the following virtual functions are pure within ‘MainClass’:
struct MainClass : public ExtendedTest1, public ITest2
^~~~~~~~~
main.cpp:4:18: note: virtual void ITest::a()
virtual void a() = 0;
^
不要嚴格判斷:)
UPD:在問這個問題之前,我真的嘗試過虛擬 inheritance 來解決我的問題,但它沒有用。 所以在建議再試一次之后,它可以工作)所以,替換這些行解決了我的問題:
struct Test1 : public ITest ---> struct Test1 : virtual public ITest
struct ITest2 : public ITest ---> struct ITest2 : virtual public ITest
我知道,我們必須避免虛擬 inheritance,但我們不能因為歷史原因和非常大量的代碼
謝謝大家的幫助!
function a
是純虛擬的,因為它沒有在層次結構MainClass
-> ITest2
-> ITest
的任何地方實現。
更多討論參見多繼承的“致命鑽石”問題。
如果您不確定自己在做什么,最簡單的解決方案是避免使用這種類型的 inheritance。 其次,您可以考慮在MainClass
中實現a
,它將 arguments 轉發到對Test1
中的a
的合格調用,如果這是您所期望的。
MainClass
有兩個基類,它們都(直接或間接)從ITest
派生。 所以MainClass
中有兩個ITest
子對象。 其中一個基類為a
提供了覆蓋,但另一個( ITest2
)沒有。 Test1
中的實現無法從ITest2
訪問。 所以MainClass
需要提供一個實現。
如果您希望甚至從ITest2
子對象調用 Test1 Test1::a
a ,您可以讓MainClass
將這些調用重定向到Test1::a
。
struct MainClass: public ExtendedTest1, public ITest2
{
// ...
void a() override { ExtendedTest1::a(); }
};
另一種可能性是虛擬 inheritance 。
您需要虛擬 Inheritance 。
虛擬inheritance可以去掉冗余功能:
相反,如果類 B 和 C 虛擬繼承自 class A,則 class D 的對象將僅包含一組來自 ZABCB142F2ED4F8EBC40AB61DZ A 的成員變量。
如果您虛擬繼承,您將擺脫重復的抽象 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.