C++枚举(enum)类型的使用
枚举是一种数据类型,它允许程序员定义一个变量并指定它可以取的那些固定值的集合。
用来表示某类事情的结果。
#include<iostream>
using namespace std;
int main()
{
enum color : unsigned int {
RED = 2,
GREEN, //默认值是3,比前一个多1
BLUE = 4
};
enum color backColor, frontColor, innerColor;
backColor = RED;
cout << backColor << endl;
switch (backColor)
{
case color::RED: cout << "红" << endl; break;
case color::GREEN: cout << "绿" << endl; break;
case color::BLUE: cout << "蓝" << endl; break;
default: cout << "errer" << endl; break;
}
enum weekday { mon = 1, tue, wed, thu, fri, sat, sun, } day; //从1开始
int k;
cout << ("请输入今天星期几(1--7):") << endl;
cin >> k;
day = (enum weekday)k;
switch (day)
{
case mon:
case tue:
case wed:
case thu:
case fri: cout << "今天上班\n" << endl; break;
case sat:
case sun: cout << "今天休息\n" << endl; break;
default: cout << "errer\n" << endl; break;
}
return 0;
}