c++ - 继承构造函数和大括号或等于初始值设定项

标签 c++ c++11 constructor inherited-constructors

我不明白为什么你不能编译一个类,它既有一个成员(不是默认可构造的),也有一个大括号或相等的初始值设定项和一个继承的构造函数。 g++ 说:

test.cpp:22:15: error: use of deleted function ‘Derived::Derived(float)’
Derived d(1.2f);

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: error: no matching function for call to ‘NoDefCTor::NoDefCTor()’
test.cpp:5:1: note: candidate:
NoDefCTor::NoDefCTor(int) NoDefCTor(int) {}

编译失败的代码(在 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 的默认构造函数(尽管显然需要它!):

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 上编译(和运行)都很好。

最佳答案

这是一个 gcc bug, #67054 .将 alltaken380 的错误报告与 OP 的案例进行比较:

// 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 接受这个程序。

关于c++ - 继承构造函数和大括号或等于初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772968/

相关文章:

c++ - 从一个动态分配的数组复制到另一个 C++

c++ - 可变参数模板运算符<<

c++ - float 的全局格式化选项

c++ - 停止 C++98 和 C++11 的隐式转换

java - 如何为子类创建构造函数

pointers - Go的构造函数为什么要返回地址?

c# - "' BaseClass ' does not contain a constructor that takes 0 arguments."部分 C#/Protobuf 类

c++ - 如何读取 stdin 以 qt 结尾?

c++ - (.eh) 在 nm 输出中意味着什么?

c++ - 使用 C++ 中的信号更改 std::thread 执行流程