Inheriting constructors and brace-or-equal initializers(继承构造函数和大括号或等号初始化器)
问题描述
我不明白为什么你不能编译一个类,它有一个成员(不可默认构造)和一个大括号或等号初始值设定项和一个继承的构造函数.g++ 说:
I don't understand why you can't compile a class which has both a member (not default constructible) with a brace-or-equal initializer and an inherited constructor. g++ says :
test.cpp:22:15: 错误:使用已删除的函数‘Derived::Derived(float)’
导出 d(1.2f);
test.cpp:22:15: error: use of deleted function ‘Derived::Derived(float)’
Derived d(1.2f);
test.cpp:16:13:注意:‘Derived::Derived(float)’被隐式删除
因为默认定义格式不正确:
使用 Base::Base;
test.cpp:16:13: note: ‘Derived::Derived(float)’ is implicitly deleted
because the default definition would be ill-formed:
using Base::Base;
test.cpp:16:13: 错误:没有匹配的函数调用‘NoDefCTor::NoDefCTor()’
test.cpp:5:1: 注意: 候选:
NoDefCTor::NoDefCtor(int) NoDefCtor(int) {}
test.cpp:16:13: error: no matching function for call to ‘NoDefCTor::NoDefCTor()’
test.cpp:5:1: note: candidate:
NoDefCTor::NoDefCTor(int) NoDefCTor(int) {}
无法编译的代码(在 g++ 5.1 下):
Code that fails to compile (under g++ 5.1):
struct NoDefCTor
{
NoDefCTor(int) {}
};
struct Base
{
Base(float) {}
};
struct Derived : Base
{
using Base::Base;
NoDefCTor n2{ 4 };
};
int main()
{
Derived d(1.2f);
}
编译的代码,但从不使用 NoDefCTor
的默认构造函数(尽管显然需要它!):
Code that compiles, but never uses NoDefCTor
's default constructor (despite apparently needing it!):
struct NoDefCTor
{
NoDefCTor(int) {}
NoDefCTor() = default;
};
struct Base
{
Base(float) {}
};
struct Derived : Base
{
using Base::Base;
NoDefCTor n2{ 4 };
};
int main()
{
Derived d(1.2f);
}
我真的不喜欢在不需要时使用默认构造函数的想法.附带说明一下,这两个版本在 MSVC14 上编译(和行为)都很好.
I don't really like the idea of having a default constructor when I don't need one. On a side note both versions compile (and behave) just fine on MSVC14.
推荐答案
这是一个 gcc 错误,#67054.将 alltaken380 的错误报告与 OP 的案例进行比较:
This is a gcc bug, #67054. Comparing the bug report by alltaken380 to the OP's case:
// gcc bug report // OP
struct NonDefault struct NoDefCTor
{ {
NonDefault(int) {} NoDefCTor(int) {}
}; };
struct Base struct Base
{ {
Base(int) {} Base(float) {}
}; };
struct Derived : public Base struct Derived : Base
{ {
NonDefault foo = 4; NoDefCTor n2{ 4 };
using Base::Base; using Base::Base;
}; };
auto test() int main()
{ {
auto d = Derived{ 5 }; Derived d(1.2f);
} }
我们甚至可以在最近的 gcc 6.0 版本上尝试这个,它仍然无法编译.clang++3.6 并且,根据 OP,MSVC14 接受这个程序.
We can even try this on recent gcc 6.0 versions, and it still fails to compile. clang++3.6 and, according to the OP, MSVC14 accept this program.
这篇关于继承构造函数和大括号或等号初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承构造函数和大括号或等号初始化器
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01