繁体   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