Blog Details

1.5 枚举类型¶

类内enum值¶

某些enum值只服务于某个类,我们可以将其声明在类的作用域内,避免污染全局作用域。

#include

class Foo {

public:

enum type {

One = 1,

Two,

Three

};

// 其他public成员

private:

// 其他private成员

};

// 使用方法

int main() {

std::cout << Foo::Three << std::endl; // 预期输出3

}

上面这种做法等价于在Foo类中定义常量,实际开发中更通用的是我们可以在Foo声明一个enum类(只有C++11及以上支持):

#include

class Foo {

public:

enum class type {

One = 1,

Two,

Three

};

// 其他public成员

private:

// 其他private成员

};

int main() {

Foo::type type = Foo::type::Three;

std::cout << int(type) << std::endl; // 预期输出3

}

编译运行:

$g++ test.cpp -std=c++11 -o test

$./test

3