枚举类型
例1.enum BUS{going, went, stay, broke}
(1)枚举类型元素为常量,不可对其赋值
如 going=9 就是错误的
但是枚举类型可在其内部对其进行赋值
例2.enum BUS{going=9, went, stay, broke}
为正确的
(2)枚举类型具有默认值,
如例1中 going=0,went=1, stay=2, broke=3
例2中 going=9,其后值为前一值加一,即went=10,stay=11,broke=12
(3)整数值不可直接赋值给枚举变量,若需要将整数值赋值给枚举变量,则必须进行强制转换
如
BUS state;
int i = 2;
state = BUS(i);
为正确赋值方法
(同样也可以使用state = static_cast<BUS>(i)进行赋值)
#include<iostream> using namespace std; enum BUS{going,went,stay,broke}; void main() { BUS state; enum BUS omit = broke; for(int count=going; count<=broke; ++count) //枚举元素值可不经转换直接赋值给整形变量 { state = BUS(count); //整型变量给枚举类型赋值则必须强制转能换 if(state == omit) cout<<"Bus was broke."<<endl; else { cout<<"Bus was Ok"; if(state == going) cout<<" and will going."<<endl; else if(state == went) cout<<" and was went."<<endl; else cout<<" and was stay."<<endl; } } }
不积小流无以成江河