c++虚拟继承
问题:
class Base {
public:
Base(Base* pParent);
/* implements basic stuff */
};
class A : virtual public Base {
public:
A(A* pParent) : Base(pParent) {}
/* ... */
};
class B : virtual public Base {
public:
B(B* pParent) : Base(pParent) {}
/* ... */
};
class C : public A, public B {
public:
C(C* pParent) : A(pParent), B(pParent) {} // - Compilation error here
/* ... */
};
在给定的位置,gcc 抱怨它无法匹配对 Base()(即默认构造函数)的函数调用。但是C并不是直接从Base继承,而是通过A和B继承。那么为什么gcc会在这里抱怨呢?
有想法吗? TIA /抢
Problem:
class Base {
public:
Base(Base* pParent);
/* implements basic stuff */
};
class A : virtual public Base {
public:
A(A* pParent) : Base(pParent) {}
/* ... */
};
class B : virtual public Base {
public:
B(B* pParent) : Base(pParent) {}
/* ... */
};
class C : public A, public B {
public:
C(C* pParent) : A(pParent), B(pParent) {} // - Compilation error here
/* ... */
};
At the position given, gcc complains that it cannot match function call to Base(), i.e. the default constructor. But C doesn't inherit directly from Base, only through A and B. So why does gcc complain here?
Ideas?
TIA
/Rob
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虚拟基类的特殊之处在于它们由最派生的类初始化,而不是由从虚拟基继承的任何中间基类初始化。哪一个潜在的多个初始化器是初始化一个基的正确选择?
如果正在构造的最派生类未将其列在其成员初始化列表中,则使用必须存在且可访问的默认构造函数来初始化虚拟基类。
请注意,即使虚拟基标识符不是相关类的直接基类,也允许在构造函数的初始值设定项列表中使用虚拟基标识符。
virtual
base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base?If the most derived class being constructed does not list it in its member initalization list then the virtual base class is initialized with its default constructor which must exist and be accessible.
Note that a virtual base identifier is allowed to be use in a constructor's initializer list even if it is not a direct base of the class in question.
您需要从 C 显式调用 Base 的构造函数:
You need to explicitly call the constructor for Base from C:
如果声明自定义构造函数,则默认构造函数将被禁用。在虚拟继承中,你需要直接调用虚拟继承的构造函数,否则它不知道是用A初始化还是用B初始化。
If you declare a custom constructor, the default constructor is disabled. In virtual inheritance you need to call the virtually inherited constructor directly because otherwise it would not know whether to initialize by A or by B.