转载:https://www.cnblogs.com/banmei-brandy/p/11263927.html
枚举类型和变量如何定义,下篇博客讲得十分详细:
https://blog.csdn.net/bruce_0712/article/details/54984371
有几个需要注意的点:
(1)在不进行强制类型转换的前提下,枚举量只能由枚举类型赋值。但是,可以把枚举量赋给其它类型(枚举量被强制转换为整型)。
(2)枚举量没有赋初值的话,会自动从0开始,按从小到大的顺序,以整数的形式初始化。
即
enum enumType {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
Monday~Sunday 会默认为0~6。将其中某个赋初值的话,下一个枚举量也会自动向上递增。
(3)枚举类型常和switch分支搭配使用。
自己简单练习了一下。用户输入0-5的数字来选择工作日,输出当天的安排。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#include<iostream> using namespace std; typedef enum workday { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, }; void chooseday(workday tempday); int main() { int today; cin >> today; chooseday(workday(today)); system ( "pause" ); } void chooseday(workday tempday) { switch (tempday) { case Sunday: { cout << "Work,and go shopping." << endl; break ; } case Monday: { cout << "Work,and read books." << endl; break ; } case Tuesday: { cout << "Travel." << endl; break ; } case Thursday: { cout << "Work,and visit friends." << endl; break ; } case Friday: { cout << "Have a party." << endl; break ; } default : cout << "Wrong input!" << endl; break ; } } |