我正在编写一个使用虚拟继承和多重继承的 C++ 代码示例。在我的代码中,我注意到我必须在每个派生类中调用
Base
类的构造函数,即使不使用传递给基类构造函数的值。为什么这是必要的,我可以避免在每个派生类中调用基类构造函数而只在 Combined
类中调用它吗?
#include <stdio.h>
class Base
{
public:
Base(int n) : n(n) {}
int n;
};
class AddsSomething1 : virtual public Base
{
public:
AddsSomething1() : Base(1)
{
printf("AddsSomething1(): base %d\n", this->n);
}
int something1;
};
class AddsSomething2 : virtual public Base
{
public:
AddsSomething2(): Base(2)
{
printf("AddsSomething2(): base %d\n", this->n);
}
int something2;
};
class AddsSomething3 : virtual public Base
{
public:
AddsSomething3() : Base(3)
{
printf("AddsSomething3(): base %d\n", this->n);
}
int something3;
};
class Combined : public AddsSomething1, public AddsSomething2, public AddsSomething3
{
public:
Combined(int n) : Base(123)
{
printf("Combined(): base %d\n", this->n);
}
};
int main()
{
Combined(123);
}
输出:
AddsSomething1(): base 123
AddsSomething2(): base 123
AddsSomething3(): base 123
Combined(): base 123
虚拟基的构造函数必须从每个派生类型调用,因为它始终是且唯一实际调用虚拟基构造函数的单个最派生类型构造函数。继承链中的每个其他基地都知道虚拟基地已经构建并跳过该步骤。
不,你无法避免调用父类构造函数,因为它们是隐式调用的。 此外,您不需要显式调用它们。 你知道,如果不调用它们,我们无法想象成功的继承。
谢谢你。