Pregunta

He creado un par de estructuras diferentes en un programa. Ahora tengo una estructura con estructuras anidadas, sin embargo, no puedo resolver cómo inicializarlas correctamente. Las estructuras se enumeran a continuación.

/***POINT STRUCTURE***/
struct Point{
    float x;                    //x coord of point
    float y;                    //y coord of point
};

/***Bounding Box STRUCTURE***/
struct BoundingBox{
    Point ymax, ymin, xmax, xmin;
};

/***PLAYER STRUCTURE***/
struct Player{
    vector<float> x;            //players xcoords
    vector<float> y;            //players ycoords
    BoundingBox box;
    float red,green,blue;       //red, green, blue colour values
    float r_leg, l_leg;         //velocity of players right and left legs
    int poly[3];                //number of points per polygon (3 polygons)
    bool up,down;               
};

Luego intento iniciar una estructura de jugador recién creada llamada jugador.

//Creates player, usings vectors copy and iterator constructors
Player player = { 
vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), //xcords of player
vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), //ycoords of playe
box.ymax = 5;               //create bounding box
box.ymin = 1;
box.xmax = 5;
box.xmin = 1;
1,1,1,                      //red, green, blue
0.0f,0.0f,                  //r_leg,l_leg
{4,4,4},                    //number points per polygon
true,false};                //up, down

Esto causa varios errores diferentes, relacionados con el cuadro. Indicar que el cuadro no tiene un identificador claro y falta una estructura o sintaxis antes de '.'.

Luego intenté crear una estructura Player e inicializar sus miembros de la siguiente manera:

Player bob;
bob.r_leg = 1;

Pero esto causa más errores, ya que el compilador cree que bob no tiene identificador o le falta alguna sintaxis.

Busqué en Google el problema pero no encontré ningún artículo que me mostrara cómo iniciar muchos miembros diferentes de estructuras anidadas dentro de la estructura (principal). Cualquier ayuda sobre este tema sería muy apreciada :-) !!!

¿Fue útil?

Solución

Lo inicializa normalmente con {...} :

Player player = { 
  vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ),
  vector<float>(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
};   

Ahora, eso está usando '' brace elision ''. Algunos compiladores advierten sobre eso, aunque es completamente estándar, porque podría confundir a los lectores. Mejor agregue llaves, para que quede claro qué se inicializa donde:

Player player = { 
  vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ),
  vector<float>(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
};

Si solo desea inicializar el miembro x de los puntos, puede hacerlo omitiendo el otro inicializador. Los elementos restantes en los agregados (matrices, estructuras) se inicializarán en valor a la derecha " valores: entonces, un NULL para punteros, un false para bool, cero para ints y así sucesivamente, y usando el constructor para tipos definidos por el usuario, aproximadamente. La fila que inicializa los puntos se ve así entonces

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

Ahora puede ver el peligro de usar una elisión con abrazadera. Si agrega algún miembro a su estructura, todos los inicializadores se '' separan '' deberían inicializar sus elementos reales, y podrían golpear otros elementos accidentalmente. Por lo tanto, es mejor que siempre use llaves cuando corresponda

Considere usar constructores. Acabo de completar su código que muestra cómo lo haría utilizando inicializadores entre llaves.

Otros consejos

Puede agregar valores predeterminados a una estructura de esta manera:

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

   float x;
   float y;
};

o

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

   float x;
   float y;
};

Para agregar esos valores durante la construcción, agregue parámetros a constructores como este:

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

   float x;
   float y;
};

e instanciarlos con estos:

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

Esto también funciona para sus otras estructuras de datos.

Parece que el cuadro delimitador solo debe contener flotantes, no Puntos?

Dicho esto, esto podría funcionar:

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

(No probado) ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top