简体   繁体   English

带联合的c ++声明Rect结构

[英]c++ Declaration Rect structure with union

I want to declare Rect structure: 我想声明Rect结构:

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

And union variables x,y to 'pos' and width,height to 'size' Vector2f structure: 并将变量x,y联合为'pos',并将width,height联合为'size'Vector2f结构:

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;

You've got the syntax wrong: the name of the struct comes before the body, not after it: 您的语法有误:struct的名称位于主体之前,而不是在主体之后:

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++. 但是请注意,“联合”在C ++中的含义完全不同。 A union is a data structure which, like a struct , groups objects. union是一种像struct一样将对象分组的数据结构。 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. 不过,虽然一的每个实例struct可以同时容纳多个值,一个实例union只能容纳在一个单一的时间值。 They have their uses, but those are pretty rare and there are usually better (and type safe) ways of accomplishing the same. 它们有其用途,但是很少使用,并且通常有更好的(且类型安全的)方式来实现。

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 演示: http//ideone.com/JgqABu

(I don't recommend doing that though; I'd just KISS and use the vectors.) (不过,我不建议您这样做;我只想亲吻并使用向量。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM