Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
问题描述
我不明白为什么在下面的代码中,当我实例化 daughter
类型的对象时,会调用默认的 grandmother()
构造函数?
I don't understand why in the following code, when I instanciate an object of type daughter
, the default grandmother()
constructor is called ?
我认为应该调用 grandmother(int)
构造函数(遵循我的 mother
类构造函数的规范),或者这段代码不应该在都是因为虚拟继承.
I thought that either the grandmother(int)
constructor should be called (to follow the specification of my mother
class constructor), or this code shouldn't compile at all because of the virtual inheritance.
这里编译器在我的背后默默地调用了grandmother
默认构造函数,而我从来没有要求它.
Here compiler silently calls grandmother
default constructor in my back, whereas I never asked for it.
#include <iostream>
class grandmother {
public:
grandmother() {
std::cout << "grandmother (default)" << std::endl;
}
grandmother(int attr) {
std::cout << "grandmother: " << attr << std::endl;
}
};
class mother: virtual public grandmother {
public:
mother(int attr) : grandmother(attr) {
std::cout << "mother: " << attr << std::endl;
}
};
class daughter: virtual public mother {
public:
daughter(int attr) : mother(attr) {
std::cout << "daughter: " << attr << std::endl;
}
};
int main() {
daughter x(0);
}
推荐答案
使用虚继承时,虚基类的构造函数直接被最派生类的构造函数调用.在这种情况下,daughter
构造函数直接调用了 grandmother
构造函数.
When using virtual inheritance, the virtual base class's constructor is called directly by the most derived class's constructor. In this case, the daughter
constructor directly calls the grandmother
constructor.
由于您没有在初始化列表中显式调用grandmother
构造函数,因此将调用默认构造函数.要调用正确的构造函数,请将其更改为:
Since you didn't explicitly call grandmother
constructor in the initialization list, the default constructor will be called. To call the correct constructor, change it to:
daugther(int attr) : grandmother(attr), mother(attr) { ... }
另请参阅此常见问题解答.
这篇关于为什么在虚拟继承中调用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在虚拟继承中调用默认构造函数?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30