enum

枚举的问题

  • 作用域问题,容易引起命名冲突。例如下面无法编译通过的:
enum Color
{
    RED,
    BLUE //重复
};
enum Feeling
{
    EXCITED,
    BLUE //重复
};

int main()
{
    Color a = BLUE; // error
    Feeling b = EXCITED;
    std::cout << a << ":" << b << std::endl;
    return 0;
}

新特性

C++11 标准中引入了“枚举类”(enum class),可以较好地解决上述问题。

enum class Color2
{
    RED=2,
    YELLOW,
    BLUE
};
Color2 c2 = Color2::RED;

类中常量

class Person{
public:
    typedef enum {
        BOY = 0,
        GIRL
    }SexType;
};

枚举常量的缺点是:它的隐含数据类型是整数,其最大值有限,且不能表示浮点。

posted on 2024-03-14 17:10  Getone超  阅读(18)  评论(0编辑  收藏  举报