How to initialize nested structures in C++?

后端 未结 3 845
南旧
南旧 2021-01-11 13:10

I have created a couple of different structures in a program. I now have a structure with nested structures however I cannot work out how to initialize them correctly. The

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 14:01

    You initialize it normally with { ... }:

    Player player = { 
      vector(xcords,xcords + (sizeof(xcords) / sizeof(float)) ),
      vector(ycords,ycords + (sizeof(ycords) / sizeof(float)) ),
      5, 1, 5, 1, 5, 1, 5, 1, 
      1.0f,1.0f,1.0f,                         //red, green, blue
      0.0f,0.0f,                              //r_leg,l_leg
      {4,4,4},                                //number points per polygon
      true,false
    };   
    

    Now, that is using "brace elision". Some compilers warn for that, even though it is completely standard, because it could confuse readers. Better you add braces, so it becomes clear what is initialized where:

    Player player = { 
      vector(xcords,xcords + (sizeof(xcords) / sizeof(float)) ),
      vector(ycords,ycords + (sizeof(ycords) / sizeof(float)) ),
      { { 5, 1 }, { 5, 1 }, { 5, 1 }, { 5, 1 } }, 
      1.0f, 1.0f, 1.0f,               //red, green, blue
      0.0f, 0.0f,                     //r_leg,l_leg
      { 4, 4, 4 },                    //number points per polygon
      true, false
    };
    

    If you only want to initialize the x member of the points, you can do so by omitting the other initializer. Remaining elements in aggregates (arrays, structs) will be value initialized to the "right" values - so, a NULL for pointers, a false for bool, zero for ints and so on, and using the constructor for user defined types, roughly. The row initializing the points looks like this then

    { { 5 }, { 5 }, { 5 }, { 5 } }, 
    

    Now you could see the danger of using brace elision. If you add some member to your struct, all the initializers are "shifted apart" their actual elements they should initialize, and they could hit other elements accidentally. So you better always use braces where appropriate.

    Consider using constructors though. I've just completed your code showing how you would do it using brace enclosed initializers.

提交回复
热议问题