4.8 枚举
枚举是表示具有共同属性的整型常量集合的用户自定义类型。这其中包含这些含义:
1. 枚举的取值只能是整数,正负皆可;
2. 枚举的取值是常量,枚举初始化后,这些值不能被改变;
3. 枚举也是一种用户自定义类型,用户定义好枚举后,可以自定义该枚举类型自身的操作,如“++”,“<<”等;
<o:p> </o:p>
枚举类型的取值隐含着这样的“潜规则”:
l 如果枚举中所有枚举值均非负,那么该枚举表示的范围,是包含这些枚举值的所有[0, 2k-1]区间中最小的那个;
l 如果枚举中包含负枚举值,那么该枚举表示的范围,是包含这些枚举值的所有[-2k, 2k-1]区间中最小的那个;
l 枚举的sizeof,就是某个能容纳其范围的整型的sizeof,但不会大于sizeof(int);
l 如果不显式的复制,那么默认枚举值将从0开始递增;
例如:
<v:shapetype id="_x0000_t202" path="m,l,21600r21600,l21600,xe" o:spt="202" coordsize="21600,21600"><v:stroke joinstyle="miter"></v:stroke><v:path o:connecttype="rect" gradientshapeok="t"></v:path></v:shapetype><v:shape id="_x0000_s1027" style="WIDTH: 374.2pt; HEIGHT: 75.7pt; mso-height-percent: 200; mso-position-horizontal-relative: char; mso-position-vertical-relative: line; mso-width-relative: margin; mso-height-relative: margin" strokeweight="1pt" strokecolor="#95b3d7" type="#_x0000_t202"><v:fill type="gradient" focus="100%" focussize="" focusposition="1" color2="#b8cce4"></v:fill><v:shadow opacity=".5" type="perspective" offset2="-3pt" offset="1pt" color="#243f60" on="t"></v:shadow><v:textbox style="mso-fit-shape-to-text: t">
enum Flags { A=1, B=2, C=9,D=7}; //Flags的取值范围是[0, 15]; Flags f1 = 5; //错误!没有定义从int到Flags的隐式类型转换; Flags f2 = Flags(14); //可以,利用显式的类型转换,而且14在[0,15]中; //虽然在Flags的定义当中没有14这个值; Flags f3 = Flags(21); //错误!21不在[0, 15]当中; |
<o:p> </o:p>
第5章 指针、数组和结构
5.1 指针
5.1.1 零
“由于各种标准转换,0可以被用于作为任意整型、浮点类型、指针、还有指向成员的指针的常量。”[1]<o:p></o:p>
“0的类型将由上下文确定”[2]<o:p></o:p>
为更好的保证类型安全,建议在C++中用0代替所有的NULL。如果不得不使用NULL,那么用下面的妥协方案:
<v:shape id="_x0000_s1026" style="WIDTH: 374.2pt; HEIGHT: 70.85pt; mso-position-horizontal-relative: char; mso-position-vertical-relative: line; mso-width-relative: margin; mso-height-relative: margin" strokeweight="1pt" strokecolor="#95b3d7" type="#_x0000_t202"><v:fill type="gradient" focus="100%" focussize="" focusposition="1" color2="#b8cce4"></v:fill><v:shadow opacity=".5" type="perspective" offset2="-3pt" offset="1pt" color="#243f60" on="t"></v:shadow><v:textbox>
#ifndef _DEF_NULL_ #define _DEF_NULL_ const int NULL = 0; #endif |