在C++中,繼承一個公共祖先並繼承一個接口(並且需要在派生類中定義一個方法)需要多重繼承嗎?例如。做我必須做以下的(而不是合併MyInterface
和ParentClass
):C++:是C++類的共同祖先和接口/原型互斥功能嗎?
class MyInterface;
class ParentClass;
class DerivedClass1;
class DerivedClass2;
class SomeOtherType;
class YetAnotherType;
class MyInterface {
public:
// Must be defined in all derived classes
virtual SomeOtherType my_common_fxn(...) = 0;
...
};
class ParentClass {
private:
// Common ancestor
YetAnotherType _useful_member;
}
class DerivedClass1 : MyInterface, ParentClass {
public:
// Do some things with _useful_member, using approach #1
SomeOtherType my_common_fxn(...);
...
}
class DerivedClass2 : MyInterface, ParentClass {
public:
// Do some things with _useful_member, using approach #2
SomeOtherType my_common_fxn(...);
...
}
void fxn_or_method_using(ParentClass);
是否有可能(優雅)合併的MyInterface
和ParentClass
功能集成到一個單獨的類? (我相信MyInterface
是ABC,我不能使用此類型作爲參數來fxn_or_method_using
)
道歉提前如果這是我已經搜查一式兩份,但沒有一個現有的C++的問題出現了排隊。 Q和/或A可能已經超過了我的(未受過訓練的)頭。
我不明白這個問題。首先:爲什麼多重繼承在這裏不好?其次:爲什麼不讓ParentClass繼承MyInterface? 如果你來自java背景:在C++中沒有這樣的接口。您可以將虛函數聲明爲0,從而使類爲抽象類型,但這並不意味着您不能將定義的函數放在那裏。即您可以使用此聲明將my_common_fxn放入ParentClass中。 –
'fxn_or_method_using'需要通過引用而不是值來引用它的參數,然後如果你願意,你可以聲明它是指'MyInterfsce'。 –
@Klemens 1.我沒有多重繼承的問題 - 實際上這就是我的代碼目前的實現方式。我正在尋找一種更加「優雅」的單一繼承,所以我不會遇到忘記兩者的問題。 – mvs