search

Home  >  Q&A  >  body text

C++,初始化一个成员变量,最好的方法是定义时初始化,还是在构造函数中初始化?

感觉在构造函数中初始化会有大量的代码,如果成员变量很多的话。。。

PHP中文网PHP中文网2814 days ago569

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:27:50

    You can refer to the "CPP Core Guidelines" recently written by Bjarne Stroustrup, which is mentioned in Article C.48:

    Prefer in-class initializers to member initializers in constructors for constant initializers

    The conclusion is to give priority to putting it in in-class, that is, initialize it when the members are defined. Because if there are multiple constructors, it may cause inconsistencies and some easy misunderstandings. Detailed answers can be found here.

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:27:50

    It depends on the specific context. Generally speaking, I suggest that the storage application be initialized when it is defined.
    Other single Init function

    reply
    0
  • Cancelreply