枚举类型 (enum)

如果某些变量有有限的值
那么我可以定义一个枚举类型,再定义一个枚举变量
枚举变量的取值就是有限的,可以防止取错值,也可提高程序的可读性

看如下代码:

#include <iostream>


enum Weekday { kMon, kTue, kWed, kThu, kFri, kSat, kSun};


int main(int argc, char *argv[])
{
    std::cout << "kMon: " << kMon << std::endl;
    std::cout << "kTue: " << kTue << std::endl;
    std::cout << "kWed: " << kWed << std::endl;
    std::cout << "kThu: " << kThu << std::endl;
    std::cout << "kFri: " << kFri << std::endl;
    std::cout << "kSat: " << kSat << std::endl;
    std::cout << "kSun: " << kSun << std::endl;

    return 0;
}

如果 enum 定义在全局作用域,那么其中的枚举值可在全局作用域中使用, 这样会污染命名空间,我们一般不会这样用

例如,可以加上命名空间

#include <iostream>


namespace Day {

enum Weekday { kMon, kTue, kWed, kThu, kFri, kSat, kSun};

}  // namespace Day


int main(int argc, char *argv[])
{
    std::cout << "kMon: " << Day::kMon << std::endl;
    std::cout << "kTue: " << Day::kTue << std::endl;
    std::cout << "kWed: " << Day::kWed << std::endl;
    std::cout << "kThu: " << Day::kThu << std::endl;
    std::cout << "kFri: " << Day::kFri << std::endl;
    std::cout << "kSat: " << Day::kSat << std::endl;
    std::cout << "kSun: " << Day::kSun << std::endl;

    return 0;
}

或者定义在一个类中

#include <iostream>


class Day {
public:
    enum Weekday { kMon, kTue, kWed, kThu, kFri, kSat, kSun};
};  // class Day


int main(int argc, char *argv[])
{
    std::cout << "kMon: " << Day::kMon << std::endl;
    std::cout << "kTue: " << Day::kTue << std::endl;
    std::cout << "kWed: " << Day::kWed << std::endl;
    std::cout << "kThu: " << Day::kThu << std::endl;
    std::cout << "kFri: " << Day::kFri << std::endl;
    std::cout << "kSat: " << Day::kSat << std::endl;
    std::cout << "kSun: " << Day::kSun << std::endl;

    return 0;
}