什么是工会? [英] What is a union?

查看:202
本文介绍了什么是工会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我的工作窗口,我发现很多数据结构的定义为结构联盟作为成员变量。这个例子是 EVT_VARIANT 在Windows中。

Recently I am working on windows and I found that lot of data structures are defined as struct with union as member variables. Example of this would be EVT_VARIANT in Windows.

我不明白这背后的目的。

I failed to understand what is the purpose behind this.

推荐答案

结构包含联盟成员是一般作为节省空间的机制来完成。如果结构可以由只有特定的会员是有效的某些子类型则联盟是一个好办法不浪费空间。

When a struct contains union members it's generally done as a space saving mechanism. If the struct can be of certain sub-types by which only certain members are valid then a union is a good way to not waste space.

例如

enum NumberKind {
  Integer, 
  FloatingPoint 
};

struct Number {
  NumberKind kind;
  union {
    int integerValue;
    float floatValue;
  };
};

在这种情况下我已经定义了一个结构它可以有型类型的数值数目:浮点和整数。这不是有效的同时拥有在同一时间因此,而不是浪费空间,通过让两个成员始终定义我创建了一个联盟这使得两者相等的存储的大小最大。

In this scenario I've defined a struct Number which can have type types of numeric values: floating point and integer. It's not valid to have both at the same time so rather than waste space by having both members always defined I created a union which makes the storage of both equal to the size of the biggest.

用法示例

void PrintNumber(Number value) {
  if (value.kind == Integer) {
    printf("%d\n", value.integerValue);
  } else {
    printf("%f\n", value.floatValue);
  }
}

这篇关于什么是工会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆