Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 多重继承,继承一个接口和一个实现_C++_Inheritance_Polymorphism_Multiple Inheritance_Mixins - Fatal编程技术网

C++ 多重继承,继承一个接口和一个实现

C++ 多重继承,继承一个接口和一个实现,c++,inheritance,polymorphism,multiple-inheritance,mixins,C++,Inheritance,Polymorphism,Multiple Inheritance,Mixins,是否可以在同一个类中同时继承接口和实现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

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

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

是否可以通过某种方式使用模板来避免对组件的显式重写和委托?

如果要避免对组件的显式重写和委托,则无法继承某种执行此绑定的接口派生类,因为您想要调用的ahas最终会出现在派生类的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;
};
通常的免责声明:虚拟继承是

我曾尝试使用模板找到更好的方法,但我认为没有一种方法可以将组件方法绑定到虚拟方法,而不必让组件从接口继承,或者手工编写绑定代码