本文介绍了继承层次结构:构造函数&析构函数执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处部分[25.14]说

Here http://www.parashift.com/c++-faq-lite/multiple-inheritance.html section [25.14] says

我尝试使用以下程序进行验证:

I tried to verify it using following program:

           A (pure virtual)
           |
           B
           |
           C
(virtual)/   \ (virtual)
       E       D
         \   /
           F
           |
           G (pure virtual)
           |
           H

每个班级都有一个c'tor和虚拟d'tor。输出如下:

each class has a c'tor and virtual d'tor. the output is as follows:

A
B
C
E
D
F
G
H
~H
~G
~F
~D
~E
~C
~B
~A
Press any key to continue . . .

但根据报价,虚拟基类的构造函数应首先执行。

but as per quote virtual base classes constructors should be executed first.

我理解错了什么?

编辑:为了澄清我的问题,根据我的理解,这种行为没有任何作用与基类是否为虚拟有关。但引用坚持使用 Virtual Base class 。我清楚了吗?还是有什么东西可疑?

To clear my question, As per my understanding this behaviour has nothing to do with whether a base class is virtual or not. but quote insists on Virtual Base class. am I clear or something fishy there?

推荐答案

如果不首先构建继承自它们的类,则无法构造虚拟基类。因此,在您的情况下,将构造非虚拟基类,因为虚拟基类依赖于它们: C 直到 A B 。因此, A B 实际上是在 C 之前构造的,即使 C 实际上是继承的。

Virtual base classes cannot be constructed if the classes they inherit from are not constructed first. So in your case, non-virtual base classes are constructed because the virtual ones depend on them: C can't be constructed until A and Bare. Therefore, A and B are indeed constructed before C, even though C is virtually inherited.

这篇关于继承层次结构:构造函数&析构函数执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:51