1:用法
enum <类型名> {<枚举常量表>};
比如:
enum weekday {Mon, Tue,……Sun};
enum自动从0开始为枚举元素赋值:
Mon = 0;
Tue = 1;
.
.
.
Sun = 6;
如果我们不想从0开始,可以:
enum weekday {Mon = 1, Tue,……Sun};
这样:
Mon = 1;
Tue = 2;
.
.
.
Sun = 7;
(这其实体现了枚举的好处有关我们有define的话
#define Mon 1
#define Tue 2
#define Wed 3
#define Thu 4
#define Fri 5
#define Sat 6
#define Sun 7
而用enum的话比较简洁)
定义枚举变量
enum set_color1{red……}color1, color2;
枚举变量可以这样赋值;
color1 = red;
color2 = color1;
不可以直接color1 = 1;//非法
但是可以强制类型转换
color1 = set_color1(1);
enum set_color2{red……};
set_color1 color3, color4;
2:注意
枚举变量可以直接输出,但不能直接输入。
不能直接将常量赋给枚举变量。
不同类型的枚举变量之间不能相互赋值。
实例
#include <iostream>
using namespace std;
enum CPU_Rank{i3 = 2, i5, i7};
enum set_color{Red, Blue, Yellow}color1;
int main()
{
CPU_Rank computer1, computer2, computer3;
computer1 = i3;
computer2 = i5;
computer3 = i7;
cout << computer1 << endl << computer2 << endl << computer3 << endl; //修改i3前, computer1为0, computer2为1, computer为2
//修改i3 = 2;
computer2 = i5;
cout << computer2 << endl; //computer2为3
color1 = set_color(1);
cout << color1 << endl;
// computer1 = 2;
//不能直接将常量赋给枚举变量
// cin >> computer1;
//枚举变量可以直接输出但不能直接输入
return 0;
}