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) { ... }
另请参阅此常见问题解答.
这篇关于为什么在虚拟继承中调用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在虚拟继承中调用默认构造函数?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01