结构变量别名

Hel*_*ate 3 c struct c99 compiler-warnings unions

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

typedef struct {
    union {
        Vector2 position;
        float x, y;
    };
    union {
        Vector2 size;
        float width, height;
    };
} RectangleF;
Run Code Online (Sandbox Code Playgroud)

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

但是当我创建这个结构的一些常量时,我​​得到一个"初始化器覆盖此子对象的先前初始化"警告:

static const RectangleF RectangleFZero = {
    .x = 0.0f,
    .y = 0.0f, // warning
    .width = 0.0f,
    .height = 0.0f // warning
}
Run Code Online (Sandbox Code Playgroud)

这样做有什么不对吗?如果没有,我怎么能摆脱这个警告?

编辑:我现在使用的解决方案:

typedef struct {
    union {
        Vector2 position;
        struct { float x, y; };
    };
    union {
        Vector2 size;
        struct { float width, height; };
    };
} RectangleF;
Run Code Online (Sandbox Code Playgroud)

Bil*_*nch 7

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

typedef struct {
    union {
        Vector2 position;
        float x;
        float y;
    };
    union {
        Vector2 size;
        float width;
        float height;
    };
} RectangleF;
Run Code Online (Sandbox Code Playgroud)

你可以通过这样做来解决它:

typedef struct {
    union {
        Vector2 position;
        struct {
            float x;
            float y;
        } position_;
    };
    union {
        Vector2 size;
        struct {
            float width;
            float height;
        } size_;
    };
} RectangleF;
Run Code Online (Sandbox Code Playgroud)

然后做:

static const RectangleF RectangleFZero = {
    .position_.x = 0.0f,
    .position_.y = 0.0f,
    .size_.width = 0.0f,
    .size_.height = 0.0f
};
Run Code Online (Sandbox Code Playgroud)

另外...

如果您的编译器支持C 2011的匿名内部结构,那么您也可以这样做:

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
};
Run Code Online (Sandbox Code Playgroud)