虚拟继承,一类足够? [英] Virtual Inheritance, one class enough?

查看:108
本文介绍了虚拟继承,一类足够?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解虚拟继承的概念,但我无法在任何地方找到答案。说你有继承类B和C的类D. B和C都继承类A.所以你可以使B和C虚拟地继承A避免A的两个实例。但是你必须在B和C指定虚拟继承



感谢

div class =h2_lin>解决方案

它们都必须 virtual 。从C ++ 11 10.1 [class.mi] / 7:



类可以同时拥有给定类型的虚拟和非虚拟基类。

  class B {/ * ... * /}; 
class X:virtual public B {/ * ... * /};
class Y:virtual public B {/ * ... * /};
class Z:public B {/ * ... * /};
class AA:public X,public Y,public Z {/ * ... * /};

对于 AA AA 的类晶格中的基类 B 的虚拟出现对应于单个 / code>子类型 AA 的对象内的子对象,以及每个其他出现的(非虚拟)基类 B AA 类类中的c $ c>对应一对一与一个不同的 B 子对象 AA 类型。给定上面定义的类 AA ,类 AA 有两个子类 B Z B 和虚拟 B 分享 X Y ,如下所示。




I understand the concept of virtual inheritance, but I couldn't find the answer to this anywhere. Say you have class D which inherits class B and C. Both B and C inherit class A. So you could make B and C virtually inherit A to avoid two instances of A. But do you have to specify virtual inheritance at both B and C or does it already create only one instance of A if one of the two virtually inherits A and the other doesn't?

Thanks

解决方案

They must all be virtual. From C++11 10.1 [class.mi]/7:

A class can have both virtual and non-virtual base classes of a given type.

class B { /* ... */ };
class X : virtual public B { /* ... */ };
class Y : virtual public B { /* ... */ };
class Z : public B { /* ... */ };
class AA : public X, public Y, public Z { /* ... */ };

For an object of class AA, all virtual occurrences of base class B in the class lattice of AA correspond to a single B subobject within the object of type AA, and every other occurrence of a (non-virtual) base class B in the class lattice of AA corresponds one-to-one with a distinct B subobject within the object of type AA. Given the class AA defined above, class AA has two subobjects of class B: Z’s B and the virtual B shared by X and Y, as shown below.

这篇关于虚拟继承,一类足够?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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