虚拟继承中的构造函数调用顺序 [英] Order of constructor call in virtual inheritance
问题描述
class A {
int i;
public:
A(){cout<<in A's def const\\\
;};
A(int k){cout<<在A const \ n; i = k; }
};
class B:virtual public A {
public:
B(){cout<<in B's def const\\\
;};
B(int i):A(i){cout<<in B const\\\
;}
};
class C:public B {
public:
C(){cout<<in C def cstr\\\
;}
C i):B(i){cout ;}
};
int main()
{
C c(2);
return 0;
}
这种情况下的输出是
在A的def const
在B const
在C const
为什么这不会进入在A const
`应该遵循1个arg构造函数调用的顺序。
但是实际上是从使用虚拟关键字从A导出B。
还有几个问题
即使我删除了虚拟关键字在上面的程序和删除所有的默认构造函数,它给出错误。所以,为什么它需要def构造函数
虚拟基类的构造函数总是从最大派生类调用,在你的情况下,最导出的类不指定 A
的初始化器,因此使用默认构造函数。
class A {
int i;
public:
A() {cout<<"in A's def const\n";};
A(int k) {cout<<"In A const\n"; i = k; }
};
class B : virtual public A {
public:
B(){cout<<"in B's def const\n";};
B(int i) : A(i) {cout<<"in B const\n";}
};
class C : public B {
public:
C() {cout<<"in C def cstr\n";}
C(int i) : B(i) {cout<<"in C const\n";}
};
int main()
{
C c(2);
return 0;
}
The output in this case is
in A's def const
in B const
in C const
Why is this not entering into in A const
`It should follow the order of 1 arg constructor call. But what actually is happening on deriving B from A using virtual keyword.
There are few more question
Even if I remove the virtual keyword in above program and remove all the default constructor it gives error. So, why it needs the def constructor
The constructors for virtual base classes are always called from the most derived class, using any arguments it might pass in. In your case, the most derived class doesn't specify an initializer for A
, so the default constructor is used.
这篇关于虚拟继承中的构造函数调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!