enum类型定义:enum类型分析



enum在实际中应用比较少容易被忽略其实enum 和 struct、都是用户自定义类型既然是自定义类型就可以有他数据成员还有成员

For example:
enum e{a=1 , b=2 , c=4};
那么:
001: enum e e1; //enum e不是对象它是类型e1才是类型enum对象!
002: e e1; //e是类型enum e简写
003: e1 = 1; //不能赋值给个用户自定义类型
004: e1 = e; //默认构造
005: e1 = e(1) //从构造enum e类型对象构造
006:e1 = a; //默认“拷贝构造

enum“取值范围”和“内存分配”


如何确定个enum取值范围?
For example:
enum e1{ a=2, b=4 };


首先找到其绝对值最大值但为了容易理解先不谈负数也就是先找到其最大值这里最大值是4
4 用 2进制表示就是 100也就是需要3bits才能最小容纳下4这个值而3bits所能表示范围是 0-7于是e1取值范围为[0,7]

现在来看看负数
enum e2{ a=-2, b=4 };
其中绝对值最大是4需要3bits才能容纳下可以取负值(而最大元素b=4不是负值)也就是说需要增加个符号位那么就需要4bits
4bits取值范围是 1000 - 0111( 2进制表示)也就是 -8 到 7(十进制表示)
enum e3{ a=-4, b=2 } 就只需要3bits取值范围是[-4,3]

简单说就是找到最少能容纳下所有元素位数

C标准规定超出枚举类型表示范围赋值结果是und也就是说 e2 x = (e2)6 是肯定正确而 e2 y = (e2)8 行为是未定义

enum内存分配如 e2 需要3bits那么C规定e2尺寸只要容得下3bits就行到底是取1个还是4个还是...那由编译器自己决定但是C标准在这里有个限制:1<= (enmu)<=()


以上内容参考自Bjarne Stroustrup The C Programming Languane .

原文如下:

4.8 Enumerations [dcl.enum]
An enumeration is a type that can hold a of values specied by the user. _disibledevent=>enum keyword {A S M ,A U T O ,B R E A K };
Each enumeration is a distinct type. The type of an enumerator is its enumeration. For example,
A U T O is of type keyword .
Declaring a variable k e y w o r d instead of plain i n t can give both the user and the compiler a h as to the ended use. For example:
void f(keyword key )
{
switch (key) {
c a s e A S M :
/ / do something
b r e a k ;
c a s e B R E A K :
/ / do something
;
}
}
A compiler can issue a warning because _disibledevent=>enum e3 {min = 10 ,m a x = 1000000}; // range 1048576:1048575
A value of egral type may be explicitly converted to an enumeration type. The result of such a conversion is und unless the value is within the range of the enumeration. For example:
enum flag { x =1 , y =2 , z =4 , e =8 }; // range 0:15
flag f1 = 5 ; // type error: 5 is not of type flag
flag f2 = flag (5 ); // ok: flag(5) is of type flag and within the range of flag
flag f3 = flag (z |e ); // ok: flag(12) is of type flag and within the range of flag
flag f4 = flag (99); // und: 99 is not within the range of flag
The last assignment shows why there is no implicit conversion from an eger to an enumeration; most eger values do not have a representation in a particular enumeration. The notion of a range of values for an enumeration dfers from the enumeration notion in the
Pascal family of languages. However, bitmanipulation examples that require values outside the of enumerators to be welld
have a long history in C and C.

The an enumeration is the s i z e o f some egral type that can hold its range and not larger than (i n t ), unless an enumerator cannot be represented as an i n t or as an u n s i g n e d i n t . Forexample, (e 1 ) could be 1 or maybe 4 but not 8 _disibledevent=>is a userd type, so users can their own operations, such as and << for an enumeration(§11.2.3).

Tags:  typedefenum javaenum enum数据类型 enum类型定义

延伸阅读

最新评论

发表评论