为什么在虚拟继承中调用Default构造函数? [英] Why is Default constructor called in virtual inheritance?
问题描述
我不明白为什么在下面的代码中,当我建议一个类型女儿
的对象时,默认 grandmother c $ c>构造函数被调用?
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);
}
推荐答案
使用虚拟继承时,虚拟基类的构造函数直接由最派生类的构造函数调用。在这种情况下,女儿
构造函数直接调用祖母
构造函数。
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) { ... }
另请参阅此常见问题条目。
这篇关于为什么在虚拟继承中调用Default构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!