C ++多重继承 - 为什么你没有工作? [英] C++ Multiple Inheritance - why you no work?

查看:166
本文介绍了C ++多重继承 - 为什么你没有工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要找出一个有趣的多重继承问题。

I am trying to figure out an interesting multiple inheritance issue.

祖父级是一个具有多个方法的接口类:

The grandparent is an interface class with multiple methods:

class A
{
public:
    virtual int foo() = 0;
    virtual int bar() = 0;
};

然后有抽象类正在部分完成这个接口。

Then there are abstract classes that are partially completing this interface.

class B : public A
{
public:
    int foo() { return 0;}
};

class C : public A
{
public:
    int bar() { return 1;}
};

我想使用的类从两个父类继承,并指定什么方法应该从哪里使用指令:

The class I want to use inherits from both of the parents and specifies what method should come from where via using directives:

class D : public B, public C
{
public:
    using B::foo;
    using C::bar;
};

当我试图实例化一个D时,我试图实例化一个抽象类时遇到错误。

When I try to instantiate a D I get errors for trying to instantiate an abstract class.

int main()
{
    D d; //<-- Error cannot instantiate abstract class.

    int test = d.foo();
    int test2 = d.bar();

    return 0;
}

有人可以帮助我理解问题以及如何最好地利用部分实现?

Can someone help me understand the problem and how to best make use of partial implementations?

推荐答案

您没有钻石继承。 D B C 自己 A 基类子对象,因为它们不会从 A 中继承。

You don't have diamond inheritance. The B and C base classes of D each have their own A base class subobject because they do not inherit virtually from A.

因此,在 D 中,真正有四个需要实现的纯虚函数成员函数: A :: foo A :: bar B A :: foo A :: bar 来自 C

So, in D, there are really four pure virtual member functions that need to be implemented: the A::foo and A::bar from B and the A::foo and A::bar from C.

你可能想使用虚拟继承。类声明和基类列表如下所示:

You probably want to use virtual inheritance. The class declarations and base class lists would look like so:

class A
class B : public virtual A
class C : public virtual A
class D : public B, public C

你不想使用虚拟继承,那么你需要覆盖 D 中的其他两个纯虚函数:

If you don't want to use virtual inheritance then you need to override the other two pure virtual functions in D:

class D : public B, public C
{
public:
    using B::foo;
    using C::bar;

    int B::bar() { return 0; }
    int C::foo() { return 0; }
};

这篇关于C ++多重继承 - 为什么你没有工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆