多重继承和纯虚函数 [英] Multiple inheritance and pure virtual functions

查看:122
本文介绍了多重继承和纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

struct interface_base
{
    virtual void foo() = 0;
};

struct interface : public interface_base
{
    virtual void bar() = 0;
};

struct implementation_base : public interface_base
{
    void foo();
};

struct implementation : public implementation_base, public interface
{   
    void bar();
};

int main()
{
    implementation x;
}

无法编译,并出现以下错误:

fails to compile with the following errors:

test.cpp: In function 'int main()':
test.cpp:23:20: error: cannot declare variable 'x' to be of abstract type 'implementation'
test.cpp:16:8: note:   because the following virtual functions are pure within 'implementation':
test.cpp:3:18: note:    virtual void interface_base::foo()

我已经试过了,发现使'interface-> interface_base'和'implementation_base-> interface_base'继承虚拟化,可以解决此问题,但是我不明白为什么.有人可以解释发生了什么吗?

I have played around with it and figured out that making the 'interface -> interface_base' and 'implementation_base -> interface_base' inheritances virtual, fixes the problem, but I don't understand why. Can someone please explain what is going on?

p.s.我故意省略了虚拟析构函数以使代码更短.请不要告诉我把它们放进去,我已经知道了:)

p.s. I omitted the virtual destructors on purpose to make the code shorter. Please don't tell me to put them in, I already know :)

推荐答案

您的继承树中有两个两个 interface_base基类.这意味着您必须提供两个实现.打电话给他们中的任何一个都会很尴尬,需要多次强制转换才能消除歧义.这通常不是您想要的.

You have two interface_base base classes in your inheritance tree. This means you must provide two implementations of foo(). And calling either of them will be really awkward, requiring multiple casts to disambiguate. This usually is not what you want.

要解决此问题,请使用虚拟继承:

To resolve this, use virtual inheritance:

struct interface_base
{
    virtual void foo() = 0;
};

struct interface : virtual public interface_base
{
    virtual void bar() = 0;
};

struct implementation_base : virtual public interface_base
{
    void foo();
};

struct implementation : public implementation_base, virtual public interface
{   
    void bar();
};

int main()
{
    implementation x;
}

对于虚拟继承,在继承层次结构中,对于所有虚拟提及,仅创建​​一个相关基类的实例.因此,只有一个foo()可以由implementation_base::foo()满足.

With virtual inheritance, only one instance of the base class in question is created in the inheritance heirarchy for all virtual mentions. Thus, there's only one foo(), which can be satisfied by implementation_base::foo().

有关更多信息,请查看此先前的问题-答案提供了一些漂亮的图表使一切更加清晰.

For more information, see this prior question - the answers provide some nice diagrams to make this all more clear.

这篇关于多重继承和纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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