1

是否可以在同一个类中同时继承接口和实现 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的纯虚函数在MyClass中通过其对Component的继承来实现。这不编译;我需要这样做:

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

是否有可能以某种方式避免显式覆盖和委托给组件,也许是通过某种方式使用模板?

4

1 回答 1

2

如果您想避免显式覆盖和委托给组件,则无法继承某种执行此绑定的接口派生类,因为您要调用的内容最终会出现在派生类的 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;
};

通常的免责声明:虚拟继承很昂贵

我试图使用模板找到更好的东西,但我认为没有办法将组件方法绑定到虚拟方法,而无需从接口继承组件,也不必手动编写绑定代码。

于 2013-10-15T02:59:04.627 回答