class A {
int i;
public:
A() {cout<<"in A's def const
";};
A(int k) {cout<<"In A const
"; 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(int i) : B(i) {cout<<"in C const
";}
};
int main()
{
C c(2);
return 0;
}
这种情况下的输出是
in A's def const
in B const
in C const
为什么这不进入in A const
`它应该遵循 1 arg 构造函数调用的顺序.但是使用 virtual 关键字从 A 派生 B 时实际发生了什么.
`It should follow the order of 1 arg constructor call. But what actually is happening on deriving B from A using virtual keyword.
还有几个问题
即使我删除了上面程序中的 virtual 关键字并删除了所有默认构造函数,它也会出错.那么,为什么它需要 def 构造函数
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
虚基类的构造函数总是从最派生的类调用,使用它可能传入的任何参数.在你的情况下,最派生的类不会't 为 A
指定初始化器,因此使用默认构造函数.
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.
这篇关于虚继承中构造函数调用的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!