【问题标题】:Struct variable alias结构变量别名
【发布时间】:2014-08-23 11:18:09
【问题描述】:

我正在尝试为这样的结构中的变量创建别名:

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

(请注意,我没有为工会命名,所以我不必写:'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;

【问题讨论】:

    标签: c struct compiler-warnings c99 unions


    【解决方案1】:

    问题是你的工会实际上是这样的:

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

    【讨论】:

    • 是的,没错。我通过尝试在没有“size_”前缀的情况下使两者都可用而使自己有点迷惑,并且不知何故忘记了这没有将 x 和 y 组合在一起。感谢您的快速回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多