Reprint Address: http://www.jellythink.com/archives/468 What is Union?
It is a common body, or also called a union. When it comes to union, which is the shared body, we have to say a struct, when we have the following definition of a struct:
struct student{ char mark; Long num; float score;};
The memory structure of the struct will be as shown (demo on x86 machine):
sizeof (struct student) has a value of 12bytes. However, when we define the union as follows,
Union test{ char Mark; Long num; float score;};
The value of sizeof (union test) is 4. Why is that? That's what needs to be said. Sometimes we need several different types of variables to exist in the same memory space, as above, we need to store a char type of mark, a long type of num variable, and a float-type score variable in a memory unit that starts at the same address. The three variables above, the char type and the long type occupy a different number of bytes of memory, but in the Union, they are all from the same address, that is, the use of overlay technology, these three variables cover each other, and this makes a number of different variables to share the same memory structure, called "Common body" The structure of the type. The structure of the Union type defined above is as follows:
It also says that the value of sizeof (union test) is 4. Then why is it 4? In general, the memory occupied by the struct struct is the sum of the memory occupied by each member (and of course the memory alignment is also considered). For union, in Rectification's C language programming, the union variable occupies a memory length equal to the length of the longest member's memory. Obviously, this is not true, and the memory-alignment issue needs to be considered for the size of the memory that the Union occupies. This is why sizeof (union test) has a value of 4.
Use Union in C
Say better, and more, after all, is to be used, the following is good to say C in the use of Union. Like a struct, a union must define a common body variable before it can be referenced. And you cannot directly reference a shared body variable, only a member in a pooled variable. Just like the union test I defined above. We cannot directly refer to Union as follows:
Union Test a;printf ("%d", a);
This direct reference is wrong because the store of a has several types, each occupying a different length of storage, and only the shared variable name A is written, so that the compiler cannot determine exactly which member of the output is the value. Therefore, it should be written as follows:
printf ("%d", A.mark);
At the same time, when using union, we also need to pay attention to the following points:
- The same memory segment can be used to hold several different types of members, but there can only be one at a time, not several at a time. In other words, only one member works at a time, and the other members do not work, that is, they do not both exist and function.
- The member that functions in the common body variable is the last member to be deposited, and when a new member is deposited, the original member loses its function. For example, the following code:
#include <iostream>using namespace std;union test{ char mark; Long num; float score;} A;int Main () { //cout<<a<<endl;//Wrong A.mark = ' B '; cout<<a.mark<<endl; Output ' B ' cout<<a.num<<endl;//98 characters ' B ' acsii value cout<<a.score<<endl;//Output error value A.num = ten; cout<<a.mark<<endl; Output NULL cout<<a.num<<endl;//Output cout<<a.score<<endl;//Output error value A.score = 10.0 ; cout<<a.mark<<endl; Output NULL cout<<a.num<<endl;//Output error value cout<<a.score<<endl;//Output 10
return 0;}
So, when using union, be careful with more than.
- Because all the member start addresses in the Union are the same, the values for &a.mark, &a.num, and &a.score are the same.
- The union variable cannot be used as a function parameter, nor can the function be brought back to the union variable, but a pointer to the union variable is available. ////has now supported
- The Union type can appear in a struct type definition, or you can define a union array, whereas a struct can also appear in a union type definition, and an array can also be a member of a union.
Logically, summing up here, the C language of union also has nothing more to say. However, there is a thing called C + +, in this C + + there is a kind of thing called class.
When union encounters an object
In the case of the Union in C alone, the sum above is sufficient, but now there is a thing called C + +; When Union encounters objects in C + +, everything gets cut and messed up. The Union usage rule summarized above is still applicable in C + +. The union was originally from the C language, and if we continue to use Union in C + + in the same way as it does, there is no problem. What if we put a class object in the Union? What would be the result? For example, the following code is available:
#include <iostream>using namespace std;class ca{ int m_a;}; Union test{ CA A; Double D;}; int main () { return 0;}
As you can see, there is no problem; if we add a constructor to a class CA, or add a destructor, we will find that the program will have an error. You cannot define static, reference-type variables because the contents of the Union share memory. Because it is not allowed in the Union to store objects with classes such as constructors, destructors, and copy constructors, the corresponding class object pointers can be stored. The compiler cannot guarantee that the constructors and destructors for the class are properly called, so a memory leak can occur. So, when we use Union in C + +, try to keep the union style in C and try not to have the union with the object.
To organize the reference version as follows:
//ConsoleApplication2.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include<iostream>#include<assert.h>using namespacestd;classca{CA (); intm_a;};classcb{intM_b;}; Union test{CharMark; Longnum; floatscore; //CA object;//ErrorCB Bobject;//correct;DAMPCA;} A;voidTestString (Char*Constp) {printf (P);}voidMakeunionasps (test& as) {printf ("%d\r\n", as. num);}voidMAKEUNIONASPS1 (test* as) {assert ( as); printf ("%d\r\n", as-num);}voidMAKEUNIONASPS2 (Test as) {printf ("%d\r\n", as. num);}int_tmain (intARGC, _tchar*argv[]) { //cout<<a<<endl;//wrongA.mark ='b'; cout<<a.mark<<endl;//output ' B 'cout<<a.num<<endl;//acsii value of 98 characters ' B 'cout<<a.score<<endl;//Output error valueA.num=Ten; cout<<a.mark<<endl;//output NULLcout<<a.num<<endl;//Output Tencout<<a.score<<endl;//Output error valueA.score=10.0; cout<<a.mark<<endl;//output NULLcout<<a.num<<endl;//Output error valuecout<<a.score<<endl;//Output TenMakeunionasps (a); MAKEUNIONASPS1 (&a); MakeUnionAsPs2 (a); TestString ("ABCDG"); return 0;}
Union (Union) and C + + (reprint and add)