簡體   English   中英

多重繼承,繼承接口和實現

[英]Multiple inheritance, inheriting an interface and an implementation

是否可以在同一類中同時繼承接口和實現mixin? 像這樣:

class Interface
{
public:
    virtual void method()=0;
};

class Component
{
public:
    void method(){ /*do something*/};
};

class MyClass : public Interface, public Component
{};

...
...
Interface* p = new MyClass(); p.method();

從Interface繼承的純虛函數是通過繼承其Component在MyClass中實現的。 這不會編譯; 我需要這樣做:

class MyClass : public Interface, public Component
{
 public:
    void method(){Component::method();} override
 };

是否有可能通過某種方式避免使用模板來顯式覆蓋和委派給Component?

如果要避免顯式重寫和委派給組件,則無法繞過某種接口派生的類來執行此綁定,因為要調用的類必須最終到達派生類的vtable中。

我想您可以使其與類鑽石的繼承結構和虛擬繼承一起使用,但是它並不十分漂亮:

class Interface
{
public:
    virtual void method()=0;
};

class Component: virtual public Interface
{
public:
    virtual void method(){ /*do something*/};
};


class MyClass : virtual public Interface, private Component
{
public:
    using Component::method;
};

通常的免責聲明:虛擬繼承非常昂貴

我試圖使用模板找到更好的方法,但我認為沒有一種方法可以將組件方法綁定到虛擬方法,而不必從組件繼承接口,也不必手動編寫綁定代碼。

暫無
暫無

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

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