C++ enum 枚举类型

1. 枚举类型浅谈

假设我们要设计一个打开文件的函数, 打开文件由三种状态: input, output 和 append. 不使用枚举, 我们可能会写出如下的代码

const int input = 1;
const int output = 2;
const int append = 3;
bool open_file(string file_name, int open_mode);

这种做法有两个缺点, 就是无法限制传递给 open_file 函数的第二个参数的取值范围, 只要传递的是 int 值, 函数本身就是合法的.第二个缺点是语义性不强, 传入的 int  变量语义不够明确

使用枚举, 可以比较完美的解决上诉问题

enum open_mode {
    input = 1, output, append
};

bool open_file(string file_name, open_mode om){}

 

2. 枚举的类型和取值

enum weather {
    sunny, cloudy, rainy, windy
};

  

 

posted @ 2013-12-11 21:19  SangS  阅读(275)  评论(0编辑  收藏  举报