gpt4 book ai didi

c - 结构变量别名

转载 作者:太空狗 更新时间:2023-10-29 16:01:40 26 4
gpt4 key购买 nike

我正在尝试为结构中的变量创建别名,如下所示:

typedef struct {
union {
Vector2 position;
float x, y;
};
union {
Vector2 size;
float width, height;
};
} RectangleF;

(请注意,我没有为 union 命名,所以我不必写:'variable.unionname.x' 等)

然而,当我创建此结构的一些常量时,我​​收到“初始化器覆盖此子对象的先前初始化”警告:

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;

最佳答案

问题是你的 union 实际上是这样的:

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
};

另外...

如果你的编译器支持C 2011's anonymous inner structs ,那么你也可以这样做:

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
};

关于c - 结构变量别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com