gpt4 book ai didi

c++ - 继承虚基类的构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:51 24 4
gpt4 key购买 nike

虚基类在最派生类中初始化,所以我的猜测是继承基类的构造函数应该也能工作:

struct base {
base(int) {}
};

struct derived: virtual base {
using base::base;
};

derived d(0);

然而,这无法用 GCC 5.2.0 编译,它试图找到 base::base(),但在 Clang 3.6.2 上工作正常。这是 GCC 中的错误吗?

最佳答案

这是 gcc 错误 58751[C++11] 继承构造函数不能与虚拟继承一起正常工作”(又名:63339使用来自虚拟基的构造函数”被隐式删除”):

来自 58751 的描述:

In the document N2540 it states that:

Typically, inheriting constructor definitions for classes with virtual bases will be ill-formed, unless the virtual base supports default initialization, or the virtual base is a direct base, and named as the base forwarded-to. Likewise, all data members and other direct bases must support default initialization, or any attempt to use a inheriting constructor will be ill-formed. Note: ill-formed when used, not declared.

Hence, the case of virtual bases is explicitly considered by the committee and thus should be implemented.

从错误报告中借用的解决方法:

struct base {
base() = default; // <--- add this
base(int) {}
};

根据错误报告,在这种情况下,构造函数 base::base(int) 由隐式生成的构造函数 derived::derived(int) 调用。

我检查过 your code不编译。但是this会调用 base::base(int) 构造函数。

关于c++ - 继承虚基类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com