自定义枚举类型
enum Roster {Tom, Sharon, Bill, Teresa, John};
默认情况下,编译器设置第一个枚举量为 0,下一个为 1,以此类推。在上述示例中,Tom 的值将是 0,Sharon 的值为 1,等等。最后一个枚举量 John 的值为 4。
换个角度想想,编译器偷偷编译了:
const int Tom = 0;
const int Sharon = 1;
const int Bill = 2;
const int Teresa = 3;
const int John = 4;
enum Colors { red, orange, yellow = 9, green, blue };
在该示例中,命名常量 red 将被赋值为 0,orange 将为 1,yellow 将为 9,green 将为 10,blue 将为 11。
enum Rooms { livingroom = 1, den, bedroom, kitchen };
在该示例中,livingroom 被赋值为 1,den 将为 2,bedroom 将为 3,kitchen 将为 4。
枚举类型实例对象的值
Roster student; // 构造
student = Sharon; // 正确
student = 1; //错误
cout << student1; // 打印出来的是一个整数值
枚举类型实例对象的判断
if (student == Bill) // 正确
if (student == 2) // 也可以,但可读性差
if (student1 <student2) // 正确