我有以下类层次结构,其中包含虚拟的
他们的构造函数是嵌套的,如下所示:
GrandParent
和非虚拟的 Parent
和 Child
:class GrandParent {
protected:
explicit GrandParent(const float &max_dur);
virtual ~GrandParent() {}
private:
const float _max_dur;
};
class Parent : public virtual GrandParent {
public:
explicit Parent(const float &max_dur = 0);
};
class Child : public Parent {
public:
explicit Child(const float &max_dur = 0);
};
他们的构造函数是嵌套的,如下所示:
// GrandParent constructor
GrandParent::GrandParent(const float &max_dur)
: _max_dur{max_dur} {}
// Use GrandParent constructor
Parent::Parent(const float &max_dur)
: GrandParent{max_dur} {}
// Use Parent constructor
Child::Child(const float &max_dur)
: Parent{max_dur} {} // <- error occurs here
我构建时出现以下错误信息:
error: no matching function for call to ‘GrandParent::GrandParent()’
看起来好像Child
构造函数被忽略了,而直接跳到了GrandParent
。将Child
构造函数修改为直接调用GrandParent
的构造函数(从而跳过一代),可以避免错误,但这似乎是错误的方法。
感谢您的帮助!
解决方案
按照463035818-is-not-a-number的答案的建议显式地调用GrandParent
的构造函数,并按照康桓瑋的建议调用Parent
的构造函数即可解决问题:
Child::Child(const float &max_dur)
: GrandParent{max_dur}, Parent{max_dur} {}
GrandParent{max_dur}
,类似于: Parent{max_dur}, GrandParent{max_dur} {}
的写法。 - 康桓瑋:Parent(max_dur)
- Refugnic Eternium