我不明白为什么在下面的代码中,当我实例化 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) { ... }
另请参阅此常见问题解答.
这篇关于为什么在虚拟继承中调用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
当没有异常时,C++ 异常会以何种方式减慢代码速In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有异常时,C++ 异常会以何种方式减慢代码速度?)
为什么要捕获异常作为对 const 的引用?Why catch an exception as reference-to-const?(为什么要捕获异常作为对 const 的引用?)
我应该何时以及如何使用异常处理?When and how should I use exception handling?(我应该何时以及如何使用异常处理?)
C++中异常对象的范围Scope of exception object in C++(C++中异常对象的范围)
从构造函数的初始化列表中捕获异常Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
C++03 throw() 说明符 C++11 noexcept 之间的区别Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)