Order of constructor call in virtual inheritance(虚继承中构造函数调用的顺序)
问题描述
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.
这篇关于虚继承中构造函数调用的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:虚继承中构造函数调用的顺序
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
