【问题标题】:Can I use a union to express a struct and multiple packed members?我可以使用联合来表达一个结构和多个打包成员吗?
【发布时间】:2019-12-16 08:38:18
【问题描述】:

假设我有一个结构,ivec2:

typedef struct ivec2 {
    int x, y;
} ivec2;

我想知道我是否可以建立类似于以下的联合:

union rectangle {
    ivec2 size; // 8 bytes; members: int x, y;
    int width, height; // 4 + 4 bytes
};

其中width 对应于size.xheight 对应于size.y

我已经看到可以这样做:

union rectangle {
    ivec2 size; // 8 bytes
    int arr[2]; // 4 + 4 bytes
};

但是我可以使用单独的成员吗?

这张图片显示了我的意思:

【问题讨论】:

  • 不,您不能对工会的个人成员这样做,因为工会的每个个人成员都与其他所有成员共享空间。

标签: c data-structures struct unions


【解决方案1】:

您要做的是在联合中嵌套一个匿名结构。

代替:

union rectangle {
    ivec2 size;
    int width, height;
};

做:

union rectangle {
    ivec2 size;
    struct {
        int width;
        int height;
    };
};

【讨论】:

  • 啊,所以通过使用匿名结构,widthheight 可以作为rectangle 的成员直接访问,对吧?这正是我需要的答案。感谢您的快速回复!
猜你喜欢
  • 2020-11-25
  • 2020-09-12
  • 2014-12-21
  • 1970-01-01
  • 2011-05-24
  • 2020-11-23
  • 2015-03-09
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多