如何在使用多重继承时避免死亡钻石? [英] How can I avoid the Diamond of Death when using multiple inheritance?

查看:270
本文介绍了如何在使用多重继承时避免死亡钻石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://en.wikipedia.org/wiki/Diamond_problem

我知道这是什么意思,但是我可以采取什么步骤来避免呢?

I know what it means, but what steps can I take to avoid it?

推荐答案

class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};

注意类D从B& C.但是, C继承自A。这将导致V表中包括A类的2个副本。

Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.

为了解决这个问题,我们需要虚拟继承。它是需要被虚拟继承的A类。因此,这将解决问题:

To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:

class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

这篇关于如何在使用多重继承时避免死亡钻石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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