简体   繁体   English

多重继承冲突

[英]Multiple inheritance conflict

I have the following code: 我有以下代码:

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
}

Now I know why this is happening, since I'm inheriting Parent then I have to implement method again. 现在我知道为什么会这样了,因为我继承了Parent,所以我不得不再次实现方法。 But it's already defined in Base class and I don't want to override that definition for every child class. 但是它已经在基类中定义了,我不想为每个子类都覆盖该定义。 I think there was some standard way of getting rid of this in c++ (telling compiler which copy of Interface should it use) I just can't remember what it was. 我认为在c ++中有一些摆脱这种情况的标准方法(告诉编译器应该使用哪个接口的副本),我只是不记得它是什么。

What you are talking about is called dominance . 您所说的是所谓的统治

From the linked article: 从链接的文章中:

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();
    }
};

You have a diamond-shaped hierarchy but are not using virtual inheritance. 您具有菱形的层次结构,但未使用虚拟继承。

As a result, you end up with two distinct virtual method() functions in your Child class. 结果,您在Child类中得到了两个不同的virtual method()函数。

One way to fix it is to move to using virtual inheritance. 解决它的一种方法是转向使用虚拟继承。 This way you'll only have a single Child::method() and won't need two implementations. 这样,您将只有一个Child::method()并且不需要两个实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM