继承hierachy:构造函数&析构函数执行序列 [英] Inheritance hierachy: Constructor & Destructor execution sequence

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

问题描述

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


要执行的第一个构造函数


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

  A(纯虚拟)
|
B
|
C
(虚拟)/ \(虚拟)
E D
\ /
F
|
G(纯虚拟)
|
H

每个类都有一个c'tor和虚拟对手。输出如下:

  A 
B
C
E
D
F
G
H
〜H
〜G
〜F
〜D
〜E
〜C
〜B
〜A
按任意键继续。 。 。

但是应该首先执行虚拟基类构造函数。

编辑:要清除我的问题,根据我的理解,这种行为没有什么关于基类是否是虚拟的。但是在虚拟基本类中强制引用。



感谢。

解决方案

如果不继承它们继承的类,则不能构造虚拟基类。所以在你的情况下,非虚拟基类是构造的,因为虚拟的依赖于它们: C 不能被构造,直到 A B 是。因此, A B 的确在 C 即使 C 实际上是继承的。


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

The very first constructors to be executed are the virtual base classes anywhere in the hierarchy.

I tried to verify it using following program:

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

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.

what did I undestand wrong?

EDIT: 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?

Thanks.

解决方案

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.

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

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