C 结构变量别名
我正在尝试为结构中的变量创建别名,如下所示:C 结构变量别名,c,struct,compiler-warnings,c99,unions,C,Struct,Compiler Warnings,C99,Unions,我正在尝试为结构中的变量创建别名,如下所示: typedef struct { union { Vector2 position; float x, y; }; union { Vector2 size; float width, height; }; } RectangleF; (请注意,我没有命名工会,因此我不必写:“variable.unionname.x”等。) 但是,当我创建此结构的某些常
typedef struct {
union {
Vector2 position;
float x, y;
};
union {
Vector2 size;
float width, height;
};
} RectangleF;
(请注意,我没有命名工会,因此我不必写:“variable.unionname.x”等。)
但是,当我创建此结构的某些常量时,会收到“Initializer overrides Pre initialization of this subobject”警告:
static const RectangleF RectangleFZero = {
.x = 0.0f,
.y = 0.0f, // warning
.width = 0.0f,
.height = 0.0f // warning
}
这样做有什么不对吗?如果没有,我怎么才能摆脱这个警告呢
编辑:我现在使用的解决方案:
typedef struct {
union {
Vector2 position;
struct { float x, y; };
};
union {
Vector2 size;
struct { float width, height; };
};
} RectangleF;
问题是你们的工会实际上是这样的:
typedef struct {
union {
Vector2 position;
float x;
float y;
};
union {
Vector2 size;
float width;
float height;
};
} RectangleF;
您可以通过执行以下操作来修复它:
typedef struct {
union {
Vector2 position;
struct {
float x;
float y;
} position_;
};
union {
Vector2 size;
struct {
float width;
float height;
} size_;
};
} RectangleF;
然后做:
static const RectangleF RectangleFZero = {
.position_.x = 0.0f,
.position_.y = 0.0f,
.size_.width = 0.0f,
.size_.height = 0.0f
};
另外。。。
如果编译器支持,则还可以执行以下操作:
typedef struct {
union {
Vector2 position;
struct {
float x;
float y;
};
};
union {
Vector2 size;
struct {
float width;
float height;
};
};
} RectangleF;
static const RectangleF RectangleFZero = {
.x = 0.0f,
.y = 0.0f,
.width = 0.0f,
.height = 0.0f
};
没错。我试着在没有“size_uu”前缀的情况下使两者都可用,并不知何故忘记了这并没有将x和y组合在一起。谢谢你的快速回复。