问题描述
此处 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
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 B
are. Therefore, A
and B
are indeed constructed before C
, even though C
is virtually inherited.
这篇关于继承hierachy:构造函数&析构函数执行序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!