[英]c++ Virtual/Non-virtual Diamond inheritance
Given the following code in C++: 在C ++中给出以下代码:
struct A {
A() { f(0); }
A(int i) { f(i); }
virtual void f(int i) { cout << i; }
};
struct B1 : virtual A {
B1(int i) : A(i) { f(i); }
virtual void f(int i) { cout << i+10; }
};
struct B2 : virtual A {
B2(int i) : A(i) { f(i); }
virtual void f(int i) { cout << i+20; }
};
struct C : B1, virtual B2 {
int i;
C() : B1(6),B2(3),A(1){}
virtual void f(int i) { cout << i+30; }
};
Can someone explain why C* c = new C()
; 有人可以解释为什么
C* c = new C()
; will print 1 23 and then 16 in that order? 会依次打印1 23和16? How does it decide which order to print in?
如何确定打印顺序? I know that the nonvirtual
B1
will be called last but why is A()
called first? 我知道非虚拟
B1
将被最后调用,但是为什么A()
被首先调用? Thanks for the help and explanation ahead of time. 感谢您的帮助和提前解释。
Because your are virtually inheriting B2
, the compiler will construct it first as to identify which variables are virtually inherited in C
before it constructs any non-virtual inheritance ( B1
). 因为您实际上是在继承
B2
,所以编译器将在构造任何非虚拟继承( B1
)之前先构造它,以识别哪些变量在C
中实际上是继承的。 Of course, A
gets constructed first because B2
needs it before it can be constructed. 当然,首先要构造
A
,因为B2
需要先构造它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.