c - 结构变量别名

标签 c struct compiler-warnings c99 unions

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

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/

相关文章:

c - GDB 无法插入断点,无法访问地址 XXX 处的内存?

C++ boolean 数组作为位域?

无法抑制对旧版 GCC 的警告

Java 编译器/eclipse 无法识别死代码

c - 为什么 GCC pad 与 NOP 一起工作?

c++ - 自己构建GCC后如何配置共享库搜索路径?

c - 使用 rand() 函数生成随机 RGB 颜色

python - 将结构中的 C 结构数组映射到 Cython

c# - 在 C# : Vector, 方向(单位向量)、点中实现这 3 个类的最佳方式

c - 'USART0_RX_vect' 的类型默认为 'int' [默认启用]