多重继承冲突

Multiple inheritance conflict

本文关键字:冲突 多重继承      更新时间:2023-10-16

我有以下代码:

class Interface
{
  virtual void method()=0;
};
class Base : public Interface
{
  virtual void method()
  {
    //implementation here
  }
};
class Parent: public Interface
{
};
class Child : public Base, public Parent
{
};
int main()
{
  Child c;//ERROR: cannot instantiate abstract class
}

现在我知道为什么会发生这种情况,因为我继承了 Parent,那么我必须再次实现方法。但它已经在基类中定义,我不想为每个子类覆盖该定义。我认为在 c++ 中有一些标准方法可以摆脱它(告诉编译器它应该使用哪个 Interface 副本)我只是不记得它是什么。

你说的叫做支配。

从链接的文章:

class Parent
{
public:
    virtual void function();
};
class Child1 : public virtual Parent
{
public:
    void function();
};
class Child2 : public virtual Parent
{
};
class Grandchild : public Child1, public Child2
{
public:
    Grandchild()
    {
        function();
    }
};

您有一个菱形层次结构,但不使用虚拟继承。

因此,您最终会在Child类中获得两个不同的虚拟method()函数。

修复它的一种方法是转向使用虚拟继承。这样,您只有一个Child::method(),不需要两个实现。

纯虚函数必须在派生类中定义。如果你不这样做,你的派生类(在本例中为"子级")本身将成为一个无法实例化的抽象类,从而导致错误。