多级继承的情况下的虚拟基本类

多级继承的情况下的虚拟基本类

本文介绍了“多级继承的情况下的虚拟基本类”有意义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例代码显示多级继承:

Consider the following sample codes which shows multilevel inheritance:

Case1: derived1 是通过虚拟继承从类 base 派生的,而类 derived2 是从类 derived1

Case1 : Here the class derived1 is derived from the class base through virtual inheritance and the class derived2 is derived from the class derived1 directly.

class base
{

};

class derived1 : virtual public base
{

};

class derived2 : public derived1
{

};

Case2:除了不涉及虚拟继承外,与Case1相同 p>

Case2 : Same as Case1 except that no virtual inheritance is involved

class base
{

};

class derived1 : public base // no virtual inheritance
{

};

class derived2 : public derived1
{

};

假设我创建一个类 derived2的对象在这两种情况下。

Suppose i create an object of the class derived2 in both cases.


  1. Case1和Case2如何在 derived2

  1. How does Case1 and Case2 differ with respect to the containment of sub-objects with in the object of derived2?

Case1对Case2有意义吗?

Does Case1 have significance over Case2 ?

PS:我清楚了解多重继承期间虚拟基类的重要性。

推荐答案

在继承层次结构中没有基类的多个实例,( virtual

Without multiple instances of a base class in an inheritance hierarchy there are (at least) two other issue to consider with virtual base classes.

首先,一个虚拟基类总是由构造中的最大派生类以及非虚拟基类之前初始化的。当中间类将参数传递给成员初始化列表中的虚拟基类构造函数时,这是最明显的。这些初始值将被忽略。它也可以对基类的构造顺序有所不同。

First, a virtual base class is always initialized by the most derived class under construction and before non-virtual base classes. This is most obvious when intermediate classes pass parameters to the virtual base class constructor in their member initialization lists. These initializers will be ignored. It can also make a difference to the order of construction of base classes.

其次,不可能执行 static_cast 从一个虚拟的基类到继承它的类。

Second, it is not possible to perform a static_cast from a virtual base class to a class that inherits from it.

这篇关于“多级继承的情况下的虚拟基本类”有意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:34