C语言的枚举

  1. enum Color{ RED, GREEN };

C语言的枚举作用域不受限,容易引起命名冲突,或者得给枚举值一些前缀用以区分相同的枚举;

C++ 经典做法

命名空间

  1. namespace color_shelly
  2. {
  3. enum Color
  4. {
  5. RED = 1,
  6. BLACK,
  7. };
  8. }

使用方式:

  1. color_shelly::Color color = color_shelly::RED;

一个更有效的办法

  1. struct ColorShelly
  2. {
  3. enum Color
  4. {
  5. RED = 1,
  6. BLACK
  7. };
  8. };

使用方法:

  1. ColorShelly::Color color = ColorShelly::BLACK;

C++11的枚举类

  • C++11引入了枚举类;
  • 新的enum的作用域不在全局;
  • 不能隐式转换成其他类型;

    1. enum class ColorShelly
    2. {
    3. RED,
    4. BLACK,
    5. GREEN,
    6. YELLOW,
    7. };

    使用方法:

    1. ColorShelly color = ColorShelly::BLACK;

    必须只能显式转换

    1. std::cout << "color:" << static_cast<int>(color) << std::endl;

    可以指定用特定的类型来存储枚举

    1. enum class ColorShelly:char
    2. {
    3. RED = 'r',
    4. BLACK,
    5. GREEN,
    6. YELLOW,
    7. };

    使用方法:

    1. std::cout << "color:" << static_cast<char>(color) << std::endl;

    输出结果:

    1. color:s

    类中的枚举类型

    1. class Color
    2. {
    3. public:
    4. typedef enum
    5. {
    6. RED = 0,
    7. BLACK,
    8. }ColorShelly;
    9. ColorShelly col;
    10. };

    使用方法:

    1. Color color;
    2. color.col = Color::BLACK;