Home  >  Q&A  >  body text

C++类内初始化与初始化列表

天蓬老师天蓬老师2714 days ago852

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:00:14

    As @GAO said, C++11's in-class initialization allows the initialization of non-static members, and you can use {} or = signs.
    Constructor initialization list and intra-class member initialization are neither good nor bad, and one can replace the other. The two methods can complement each other. In-class initialization has some benefits:
    1. When you have multiple constructors, if you use an initialization list, each constructor must be written once, which is annoying and produces duplicate code, making modifications easy to miss. If these members are initialized within the class, there is no need to list them in the initialization list.
    2. In-class initialization, the order between members is implicit, which will be somewhat convenient. If you use an initialization list, it is in order. If the order is wrong, the compiler will warn you.
    3. For simple classes or structures without constructors, you can directly use in-class initialization to initialize directly at the same time as member declaration, which is convenient.

    Be careful when initializing members of some class types. If there are dependencies between members, it is safer to use an initialization list to explicitly indicate the construction (initialization) order of these members.

    If a member has used in-class initialization, but is listed in the initialization list of the constructor, the compiler will give priority to the latter, and the in-class initialization will be ignored. If some members have different default values ​​when using different constructors, in this case, an initialization list must be used. At the same time, other members can still use in-class initialization.

    In-class initialization is definitely not a solution to the problem of undefined built-in types being initialized by default. A very important principle of object-oriented programming is that programmers are responsible for ensuring that when an object is created, each member of it must be initialized. This is a design issue and basic awareness, no matter which method is used to initialize it.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:00:14

    It seems that in-class initialization is supported after C++11. In-class initialization was not allowed before

    class A{
        static const int a = 7; //C++98允许
        int b = 8; //C++11允许,而98不允许
    }

    I personally think that in-class initialization will become mainstream with C++11.

    reply
    0
  • Cancelreply