1. union
union和struct的结构相同,都可以有多种不同的类型变量,但是用途有区别。union一次只能有一个变量有值。
E.g. struct里面有int, string和double. union里面有int OR string OR double.
In .h
union unionId {
int id_int;
double id_double;
};
In .cpp file:
unionId ui;
ui.id_int = 1;
cout << "The value of a union is " << ui.id_int << " double value is " << ui.id_double <<endl;
ui.id_double = 12.3;
cout << "The value of a union is " << ui.id_int << " string value is " << ui.id_double <<endl;
Result is:
The value of a union is 1 double value is 4.94066e-324
The value of a union is -1717986918 string value is 12.3
One use for a union is to save space when a data item can use two or more formats but never simultaneously. For example,
In .h file:
struct {
string name;
int size[4];
union id {
int id_int;
char id_chars[20];
} testid;
} test;
In .cpp file:
cout << "Enter a or b";
cin >> test.name;
cout<<endl;
if (test.name=="a") {
test.testid.id_int = 1;
} else {
cout << "Enter struct test id in char[] format: ";
cin>> test.testid.id_chars;
}
cout << " The id of test struct is " << test.testid.id_int << " string format is " << test.testid.id_chars <<endl;
Result is:
Enter a or b: b
Enter struct test id in char[] format: afdsga
The id of test struct is 1935959649 string format is afdsga
一个匿名的union没有名字, 那么它的所有变量就会共享一个地址,只有其中的一个才是当前的。 An anonymous union has no name; in essence, its members become variables that share the same address. Naturally, only one member can be current at a time
struct {
string name;
int size[4];
union {
int id_int;
char id_chars[20];
};
} test;
test.id_int OR test.id_chars
2. Enumeration
Enumeration提供了另一种方式来声明const变量。 它的声明方式与struct一样。
By default, enum的第一个元素的值是0, 后续元素在前一个元素的基础上+1。
enum Color { red, green, blue};
- color是新定义的一个type;
- red, green, blue叫做enumerators. By default, its values start from 0, red=0, green=1, blue=2.
Color sColor;
赋值方式:
Color sColor;
sColor = Color(0); //强制转换
sColor = green; //用enum Color中的成员
int iColor = sColor; //用于整数运算
cout << "the value of enum is "<< sColor << " and int is "<<iColor<<endl;
Result is:
the value of enum is 1 and int is 1.
- Enum可以直接将成员赋值给自己类型的变量; E.g. sColor = green;
- Enum可以promoted to int type; E.g. int iColor = sColor;
- Enum不可以直接用整数赋值, 需要类型转换; E.g.
- sColor = 0; //not valid
- sColor = Color(0);
- Enum的变量可以用于运算. E.g. iColor = 3+sColor; if(sColor| 1) {xxx;}
enum的设值
因为enum实际上是const变量的另一种定义方式,我们可以指定enum的元素的值。
- 如果多个元素的值是挨着的。可以用下面enum Values的方式;
- 如果元素的值是间隔的,可以用Bits or BigStep的方式;
enum Bits {one = 1, two=2, four=4};
enum Values {zero, null = 0, pos, positive = 1};
enum BigStep {firstStep, bigstep = 100, ThridStep};
cout <<"values of Bits:" << one <<" "<<two<<" "<<four<<endl;
cout <<"values of Values: " << zero <<" "<<null<<" "<<pos<< " "<<positive<<endl;
cout <<"values of BigStep: " << firstStep << " "<< bigstep <<" "<< ThridStep<<endl;
Result is:
values of Bits:1 2 4
values of Values: 0 0 1 1
values of BigStep: 0 100 101