问题描述
我不明白为什么在下面的代码中,当我实例化 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) { ... }
另请参阅此常见问题解答.
这篇关于为什么在虚拟继承中调用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!