接口的钻石问题
我使用许多抽象类,它们仅定义纯虚函数和虚拟(非纯)析构函数。
不使用虚拟继承,钻石继承结构还可以吗? (我想确保即使某些程序员不知道他应该使用虚拟继承也不会出现任何问题。)有什么好的资源可以对这个主题进行简短但完整的概述?
谢谢!
I am using many abstract classes which define only pure virtual functions plus a virtual (non pure) destructor.
Is it still ok to have a diamond inheritance structure without using virtual inheritance? (I'd like to make sure that there are no problems even if some programmer does not know he should use virtual inheritance.) What's a good resource which gives a short but complete overview of this topic?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。如果没有虚拟继承,继承图就不是菱形。如果
Derived
继承自Left
和Right
,并且两者均非虚拟地从Base
派生,那么将有两个每个派生
对象的Base
子对象。You can't. Without virtual inheritance, the inheritance graph just isn't a diamond. If
Derived
inherits fromLeft
andRight
, and both derive non-virtually fromBase
, then there will be twoBase
subobjects perDerived
object.虚拟继承是您获得钻石的机制 - 如果您不使用虚拟继承,那么您将获得公共基类的两个不同副本 - 这不再是真正的钻石,并且可能不是您想要的。
Virtual inheritance is the mechanism by which you get a diamond - if you don't use virtual inheritance then you two different copies of the common base class - which isn't really a diamond any more and probably not what you want.
此常见问题解答通过示例提供了多重继承的良好答案。
对于钻石,你必须有虚拟继承。
This faq provides good answers to multiple inheritance with examples.
For the diamond, you have to have virtual inheritance.