[英]Multiple virtual inheritance and constructor call of base class
There is this code: 有这个代码:
#include <iostream>
class Bazowa
{
int x;
public:
Bazowa() : x(55){}
Bazowa(int x_) : x(x_) {}
void fun()
{
std::cout << x << "fun\n";
}
};
class Pochodna1 : virtual public Bazowa
{
public:
Pochodna1() : Bazowa(101) {}
};
class Pochodna2 : virtual public Bazowa
{
public:
Pochodna2() : Bazowa(103) {}
};
class SuperPochodna : public Pochodna1, public Pochodna2
{
public:
SuperPochodna() : {}
};
int main() {
SuperPochodna sp;
sp.fun(); // prints 55fun
return 0;
}
After execution of this program, it will print "55fun". 执行该程序后,将打印“55fun”。 What happened to constructor calls in class Pochodna1 and Pochodna2 - are they ignored? 在Pochodna1和Pochodna2类中构造函数调用发生了什么 - 它们被忽略了吗? Why member 'x' of class Bazowa is set to '55', but not '101' or '103'? 为什么班级Bazowa的成员'x'被设置为'55',而不是'101'或'103'?
Virtual base constructors are always called from the final leaf class. 始终从最终叶类调用虚拟基础构造函数。 None of the other constructors for the virtual base are called. 不会调用虚拟基础的其他构造函数。 In your case SuperPochodna()
is calling Bazowa()
and the calls to Bazowa(int)
in Pochodna1
and Pochodna2
are not used. 在你的情况下, SuperPochodna()
调用Bazowa()
并且不使用Pochodna1
和Pochodna2
中对Bazowa(int)
的调用。
See http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14 or just google "virtual base constructor". 请参阅http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14或只是谷歌“虚拟基础构造函数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.