About default C struct values, what about this code?

后端 未结 8 1509
时光说笑
时光说笑 2020-12-31 15:27

I\'m trying to create structs with default values. I don\'t know how to accomplish this because every code that I see, is about initialising, and I would it for the natural

8条回答
  •  清歌不尽
    2020-12-31 16:04

    Update: This answer assumes we 're talking about C++ because the code posted in the answer is not legal C.

     struct a {
         a() : i(0), j(0) {}   // constructor with initialization list
         int i;
         int j;
     }
    

    The line marked with the comment is simply the constructor for instances of struct a (reminder: structs are just like classes, except that the default member visibility is public instead of private).

    The part after the : is called an initialization list: it allows you to initialize the members of the struct with values (either constants or passed as constructor parameters). Initialization of members in this list happens before the body of the constructor is entered. It is preferable to initialize members of classes and structs this way, if at all possible.

    See also C++: Constructor versus initializer list in struct/class.

提交回复
热议问题