- 一般在大括号内声明的名称(name,或者严谨点说标识符)的可见范围是限制在大括号内的。然而C++98中的
enum不同:它内部定义的名称会泄露到定义enum自身的区域中。因此也得名 unscoped enum:
enum Color {
black, white, red };
auto white = false; // VS报错: main::white重定义
- C++11版本的 scoped enums 通过
enum class定义,不会导致名称的泄露:
enum class Color {
black, white, red };
Color c = white; // error, 找不到white
Color c = Color::white; // ok
auto c = Color::white; // ok
- scoped enums 的第二个好处:枚举值为强类型,不会被意外地隐式转为整型(甚至接着被转为浮点型)。如果真的想进行转换,用最正确的方法,调用
cast:
enum class Color {
black, white, red };
Color c = red; // error
Color c = Color::red; // ok
if (c < 14.5) {

本文对比了C++98中的unscoped enum与C++11引入的scoped enum的区别,包括名称作用域、类型转换、底层类型指定及前向声明等方面,并探讨了它们各自的适用场景。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



