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.
这篇关于虚继承中构造函数调用的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:虚继承中构造函数调用的顺序
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
