0

I want to declare Rect structure:

struct{
   float x,y;
   float width,height;
}Rect;

And union variables x,y to 'pos' and width,height to 'size' Vector2f structure:

struct{
   float x,y;
}Vector2f;

How can i do it with union?

Rect rect; 
//rec.x; rec.y; rect.pos; rect.pos.x; rect.pos.y; 
//rect.width; rect.height; rect.size; rect.size.x; rect.size.y;
Artem Romanov
  • 166
  • 1
  • 14

2 Answers2

2

You’ve got the syntax wrong: the name of the struct comes before the body, not after it:

struct Rect {
   float x, y;
   float width, height;
};

There, now you’re good to go.

But note that “union” means something completely different in C++. A union is a data structure which, like a struct, groups objects. But while every instance of a struct can hold multiple values simultaneously, an instance of a union can only hold a single value at a time. They have their uses, but those are pretty rare and there are usually better (and type safe) ways of accomplishing the same.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

You're looking for anonymous unions. The syntax is:

struct Rect {

   union {
       Vector2f pos;
       struct {
           float x,y;
       };
   };
   union {
       Vector2f size;
       struct {
           float width, height;
       };
   };

};

Demo: http://ideone.com/JgqABu

(I don't recommend doing that though; I'd just KISS and use the vectors.)

Kos
  • 70,399
  • 25
  • 169
  • 233