我认为你是误会工会。
使用工会背后的想法是脚趾节省内存……
是的,那年代的一个原因
…和获得的结果相当于结构……
没有
it s 没有t equivalent. They looks similar in source code, but it is a completely different thing. Like apples and airplanes.
Unions are a very, very low level construct that allows you to see a piece of memory as if storing any of its "members", but you only can use one at a time. Even the use of the word "member" is extremely misleading. They should be called "views" or something, 没有t members.
当你写:
union ABCunion
{
int a;
double b;
char c;
} myAbc;
You are saying: "take a piece of memory big e没有ugh for the biggest among an int, a char and a double, and lets call it myAbc.
In that memory, 没有w you can store either an int, or a double, or a char. If you store an int, and then store a double, the int is gone forever.
点什么呢?
有两个主要用途工会。
一)歧视存储
这上面所做的。我拿一块内存,赋予它不同的含义取决于上下文。有时是显式的上下文中(你保留一些变量,表示“类”的变量存储),有时它可以隐式(基础部分的代码,您可以告诉哪一个必须使用)。无论哪种方式,代码需要能够算出来,或者你不能够做任何合理的变量。
一个典型的例子(显式)是:
struct MyVariantType
{
int typeIndicator ; // type=1 -> It s an int,
// type=2 -> It s a double,
// type=3 -> It s a char
ABCunion body;
};
For example, VB6 s "Variants" are Unions 没有t unlike the above (but more complex).
b) Split representation
This is sometimes useful when you need to be able to see a variable as either a "whole" or as a combination of parts. It s easier to explain with an example:
union DOUBLEBYTE
{
struct
{
unsigned char a;
unsigned char b;
} bytes;
short Integer;
} myVar;
这年代短int“联合”两个字节。现在,您可以查看相同的值作为一个短整型(myVar.Integer),或者您可以简单地研究单个字节(myVar.bytes价值的一部分。一个和myVar.bytes.b)。
Note that this second use is 没有t portable (I m pretty sure); meaning that it s 没有t guaranteed to work across different machine architectures; but this use is absolutely essential for the kind of tasks for which C was designed (OS implementation).