枚举类型的声明如下:
enum 枚举类型名 {变量值列表};
e.g. enum Weekday {SUN, MON, TUE, WEN, THU, FRI, SAT};
例题:某比赛结果有四种,(WIN, LOSE, TIE, CANCEL),利用枚举类型变量顺序输出这四种情况
分析:由于比赛结果只有4种可能,所以可以声明一个枚举类型,用一个枚举类型的变量来存放比赛结果。
代码:
#include <iostream>
using namespace std;
enum GameResult{WIN, LOSE, TIE, CANCEL};
int main()
{
enum GameResult result;
enum GameResult omit = CANCEL; //声明变量时可以不写关键字
for (int count = WIN ; count <= CANCEL; count ++) //隐含类型转换
{
result = GameResult(count); //显示类型转换
if(result==omit)
{
cout<<"This game was cancelled"<<endl;
}
else
{
cout<<"This game was played";
if(result == WIN){
cout<<"and we win!"<<endl;
}
else{
cout<<"but we lost."<<endl;
}
}
}
return 0;
}
运行结果:
The game was played and we won!
The game was played and we lost.
The game was played
The game was cancelled