例如:
enum spectrum{red,orange,yellow,green,blue,violet,indigo,ultraviolet};
spectrum被称为枚举类型。
可以用枚举名来声明这种类型的变量。
spectrum band;
band=blue;//valid
band=20000;//invalid
枚举只定义了赋值运算符,不能进行算术运算符。
band=orange;//valid
++band;//invalid
band=orange+red;//invalid
枚举量是整型,可被提升为int类型,但int类型不能自动转换为枚举类型。
int color=blue;//valid,spectrum type promoted to int
band=3;//invalid,int not converted to spectrum
color=3+red;//valid,red convert to int
2.设置枚举类型的值。
enum bits{one=1,two=2,four=4,eight=8};
enum bigstep{first,secong=100,third};
enum {zero,null=0,one,numero_uno=1};
zero 与null 值为0,而one与umero_uno=1值都为1。
3.枚举类型的取值范围。
每个枚举类都有取值范围,通过强制类型转换,可将取值范围中的任何整数值赋给枚举变量,即使这个值不是枚举值。
enum bits{one=1,two=2,four=4,eight=8};
bits myflag;
myflag=bits(6);//valid,because 6 is in bits range
//该枚举类型的范围为0~15
取值范围的定义:
找到枚举类型中的上限值的最小的二次幂减1.