[英]Filling out abstract class members by deriving from concrete class
假設我有一個繼承自另一個接口的接口(純抽象類)
class BaseInterface
{};
然后另一個接口構建在BaseInterface上
class ExtendedInterface : public BaseInterface
{};
現在,我有一個實現BaseInterface的具體類:
class Base : public BaseInterface
{};
現在,我想實現ExtendedInterface,但由於我已經有Base,我想用base填充BaseInterface成員。 例如:
class Extended : public ExtendedInterface, public Base
{};
這似乎不起作用。 我得到的投訴是我無法實例化擴展,因為它是一個抽象類。 我可以讓它工作的唯一方法是使用虛擬繼承,但后來我得到關於繼承通過優勢的編譯器警告。
使用多重繼承, Extended
從BaseInterface
繼承兩次。 這意味着有兩個獨立的BaseInterface
子對象:
一個是通過具體的Base
類繼承的,它覆蓋了所有純虛函數。
但是另一個是通過ExtendedInterface
類繼承的,它仍然是抽象的。
因此,由於Extended
某些子對象仍具有純虛函數,因此您的類仍然是無法實例化的抽象類。
盡管您顯然希望只有一個BaseInterface
進行多重繼承,但您需要使用虛擬繼承:
class BaseInterface
{ virtual void test()=0; }; // abstract class
class ExtendedInterface : public virtual BaseInterface // virtual inheritance
{}; // abstract class
class Base : public virtual BaseInterface // virtual inheritance
{ void test() override {} }; // concrete class
class Extended : public ExtendedInterface, public Base // multiple
{}; // thanks to virtual inheritance, concerete class
有了這個邏輯, Extended
只有一個BaseInterface
,虛擬函數被覆蓋,你可以實例化它。
這是一個在線演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.