加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

结构变量别名

发布时间:2020-12-16 09:53:04 所属栏目:百科 来源:网络整理
导读:我正在尝试为结构内的变量创建一个别名,如下所示: 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’等)

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

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

另外…

如果您的编译器支持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,.width = 0.0f,.height = 0.0f
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读