search

Home  >  Q&A  >  body text

C++ class 初始化赋值问题?

第一个有自动生成默认构造函数吗?
为什么第二个不可以编译通过?

伊谢尔伦伊谢尔伦2803 days ago427

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:24:50

    Does the first one automatically generate a default constructor?

    Yes, when there is no any user-defined constructor in a class, the compiler will generate a default constructor. See Default constructors.


    Why doesn’t the second one compile?

    If a class wants to use a brace list to initialize members, then the class must meet the conditions of aggregate class. Among the conditions of aggregate class, one is

    The

    class does not contain any in-class initializer.

    In the second example class definition of the subject, both members a and b use in-class initializer, so they are not aggregate class, so

    cannot be used
    NoDefault y = {2, 2};
    Initialized using

    .

    Note: According to aggregate initialization, this condition will be deleted in C++17.

    reply
    0
  • Cancelreply