c++ - 逐字段构造函数生成的规则是什么?

标签 c++ c++11 initializer-list aggregate-initialization

我发现对类使用初始化列表语法的可能性取决于类字段是否具有默认值。为什么?

确切地说,考虑以下代码:

class S
{
    public:
        int a;
};
...
int a;
S s{ a };

它编译没有任何问题。但是如果我在类字段中添加一个默认值,它就会停止构建:

class S
{
    public:
        int a = 0;
};
...
int a;
S s{ a };

Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'S'

为什么?还有什么影响这种构造函数的生成?

最佳答案

C++14 中,您的代码是有效的并且应该使用任何与 C++14 兼容的编译器进行编译。


C++11 中:

如果您没有 a 的默认值,则您的类型是聚合,因此 aggregate initialization可以执行:

An aggregate is one of the following types:

  • array type

  • class type (typically, struct or union), that has

    • no private or protected non-static data members
    • no user-provided constructors , including those inherited from public bases (since C++17) (explicitly defaulted or deleted constructors are allowed) (since C++11)
    • no virtual, private, or protected (since C++17) base classes
    • no virtual member functions
    • no default member initializers (since C++11, until C++14)

一旦您为属性 a 添加了默认值,您的聚合初始化就无法再执行,因为您的类型不再是聚合。

关于c++ - 逐字段构造函数生成的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099467/

相关文章:

c++ - std::optional<boost::asio::ip::tcp::socket> 使用 socket.emplace() 初始化

c++ - 编译嵌套参数包代码时出现 gcc 段错误

c++ - 无法在 cbegin 中定义 initializer_list

c++ - 为什么将这些 C++ header 指定为包含 <initializer_list>?

c++ - 为什么 GetDC 对同一个对象返回不同的值?

c++ - 重载 'swap(float&, float&)' 的调用不明确

c++ - C 和 C++ 调用约定之间有什么区别?

c++ - 用 vector 模拟行星轨道

c++ - 将纳秒(从午夜开始)转换为可打印时间?

c++ - 为什么我的编译器无法识别出这种转换,它何时存在?