复制构造函数大括号括号初始化 [英] Copy constructor curly braces initialization

查看:218
本文介绍了复制构造函数大括号括号初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我们可以初始化一个类的对象,我们没有定义
任何构造函数:

"we can initializate objects of a class for which we have not define any constructor using:


  • 成员初始化。

例如:

    struct Work {
      string author;
      string name;
      int year;
    };

    Work s9 { "Bethoven",
              "Symphony No. 9 in D minor, Op. 125; Choral",
              1824
            };                    // memberwise initialization

    Work currently_playing {s9};  // copy initialization
    Work none {};                 // default initialization


C ++编程语言第4版第17.3.1章

The C++ Programming Language 4th Ed. Chapter 17.3.1

例如:

   struct Data
     {
        int mMember1;
        float mMember2;
        char mMember3;
     };

     int main()
     {
         Data aData_1{1,0.3,33};
         Data aData_2{aData_1};

         return EXIT_SUCCESS;
     }

这必须工作,虽然我得到一个编译器错误与GCC作为Clang。错误是无法转换数据到int在两个编译器。但实现复制构造函数这个错误消失或者没有插入它,但使用圆括号语法。问题是有点蠢,改变圆括号的问题得到解决的卷曲。但为什么没有遵循TC ++ PL的规则,是一个编译器问题,或者我误解了什么?先感谢。

This must work, althought I get a compiler error as much with GCC as with Clang. The error is "cannot convert Data to int" in both compilers. However, implementing the copy constructor this error disappear or without implenting it but using the round braces syntax. The problem is a little stupid and changing the curly for the round braces the problem get solved. But why the rules of TC++PL are not followed?, is a compilator issue or I'm misunderstanding something?. Thanks in advance.

推荐答案

我认为行为符合8.5.4(列表初始化),第3句:

I think the behaviour conforms with 8.5.4 (List initialization), sentence 3:


类型 T 的对象或引用的列表初始化定义如下:

List-initialization of an object or reference of type T is defined as follows:

- 如果 T 是聚合,则执行聚合初始化(8.5.1)。

— If T is an aggregate, aggregate initialization is performed (8.5.1).

[...]

- 否则,如果初始化器列表有一个 E [...]对象或引用从该元素初始化;

— Otherwise, if the initializer list has a single element of type E [...] the object or reference is initialized from that element;

但是第一项优先:由于 Data 确实是一个聚合,所以不会考虑one-element-list子句。

You were expecting the second item in my abbreviated quote to apply, but the first item takes precedence: Since Data is indeed an aggregate, the one-element-list clause is never considered.

您在图书中的报价似乎是已知错误。该语言据称将被修正以匹配C ++ 14中的书。

Your quote from the book appears to be a known error. The language is allegedly going to be fixed to match the book in C++14.

这篇关于复制构造函数大括号括号初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆