枚举类型

枚举类型

1. 定义

枚举是用来代表整数常量的符号

默认形式:

enum 枚举名 {枚举元素, ...};

2. 枚举元素的值

2.1 默认

枚举元素的值,默认从0开始,逐项+1

// 从SUNDAY开始,值分别是0,1,……,6
enum DAY {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,FRIDAY, SATURDAY};

2.2 全部赋值

// 枚举元素的值以赋值结果为准
enum DAY {
    SUNDAY = 20, 
    MONDAY = 30, 
    TUESDAY = 100, 
    WEDNESDAY = 1024, 
    THURSDAY = 580,
    FRIDAY = 699, 
    SATURDAY = 21
};

2.3 部分赋值

与默认情况相同,在枚举元素无赋值的情况下,值默认为上一枚举元素的值+1,首个枚举元素的值默认为0。

// SUNDAY = 0,TUESDAY = 31,WEDNESDAY = 32
// 其余枚举元素的值以赋值结果2为准
enum DAY {
    SUNDAY, 
    MONDAY = 30, 
    TUESDAY, 
    WEDNESDAY, 
    THURSDAY = 580,
    FRIDAY = 699, 
    SATURDAY = 21
};

3. 枚举变量的定义方式

3.1 先定义枚举类型,再定义枚举变量

// 定义枚举类型
enum DAY {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}; 
// 定义枚举变量
enum DAY day;

3.2 同时定义枚举类型和枚举变量

enum DAY {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} day; // 已经完成了对于枚举变量day的定义

3.3 忽略枚举名,直接定义枚举变量

enum {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} day; // 仅定义了枚举变量day

3.4 结合typedef关键字

使用typedef关键字,创建了一个新的类型名,简化了enum类型的声明,无需再写enum

typedef enum {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} DAY;
DAY today = WEDNESDAY; // 无需写成enum DAY day;

4. 总结

  1. 例子中各枚举元素的值分别是多少?
enum day {
    SUNDAY, 
    MONDAY = 30, 
    TUESDAY, 
    WEDNESDAY, 
    THURSDAY = 580,
    FRIDAY = 699, 
    SATURDAY = 21
};
  1. 请说明枚举类型4种定义方式,并举出具体的例子。

热门相关:隐婚365天:江少,高调宠!   我的学姐会魔法   修罗武帝   帝少夜宠:小甜妻,乖!   永恒王权