- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下具有虚拟 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's answer 修复显式调用 GrandParent
的构造函数和康桐蔚的建议,以便也调用 Parent
的构造函数:
Child::Child(const float &max_dur)
: GrandParent{max_dur}, Parent{max_dur} {}
最佳答案
来自faq :
What special considerations do I need to know about when I inherit from a class that uses virtual inheritance?
Initialization list of most-derived-class’s ctor directly invokes the virtual base class’s ctor.
Because a virtual base class subobject occurs only once in an instance, there are special rules to make sure the virtual base class’s constructor and destructor get called exactly once per instance. The C++ rules say that virtual base classes are constructed before all non-virtual base classes. The thing you as a programmer need to know is this: constructors for virtual base classes anywhere in your class’s inheritance hierarchy are called by the “most derived” class’s constructor.
Child
的构造函数直接调用了GrandParent
的构造函数,因为GrandParent
是一个虚基。因为您没有显式调用它,所以调用了默认构造函数,但是 GrandParent
没有默认构造函数。
Modifying the Child constructor to directly call the GrandParent constructor (thus skipping a generation), I can bypass the error but it seems like the wrong approach.
这是完全正确的方法。 Child
的构造函数确实调用了 GrandParent
的构造函数,当 GrandParent
是虚拟基础并且 Child
时,您对此无能为力> 是最派生类。您可以做的是:选择正确的构造函数,而不是让编译器尝试调用不存在的默认构造函数。
关于c++ - 子构造函数使用祖父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69614345/
您好,我想以如下图所示的层次结构方式显示数据 这是我的数据库表结构 这是我使用过的查询,但它不是我想要的完美结果 SELECT t1.parent_id AS primary_Id, t2.paren
给定 3 个 Azure DevOps 管道(可能存在更多),如下所示: 构建、单元测试、发布工件 部署暂存、集成测试 部署生产,烟雾测试 如何确保流水线 3 下载流水线 1 中发布的特定工件? 我所
我是一名优秀的程序员,十分优秀!