How to initialize nested structures in C++?

后端 未结 3 874
南旧
南旧 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条回答
  •  猫巷女王i
    2021-01-11 13:48

    You can add default values to a structure like so:

    struct Point{
       Point() : x(0), y(0)
         { };
    
       float x;
       float y;
    };
    

    or

    struct Point{
       Point() 
         { 
           x = 0;
           y = 0;
         };
    
       float x;
       float y;
    };
    

    For adding those values during construction, add parameters to constructors like this:

    struct Point{
       Point(float x, float y) 
         { 
           this->x = x;
           this->y = y;
         };
    
       float x;
       float y;
    };
    

    and instantiate them with these:

    Point Pos(10, 10);
    Point *Pos = new Point(10, 10);
    

    This also works for your other data structures.

提交回复
热议问题