C++面试准备 为什么使用scoped enum
C++提供2种方式来定义枚举enum,如下所示:
enum Gender {Male, Female}; // C++98提供的unscoped enum enum class Color {Black, Red}; // C++11开始提供的另外一种新的定义enum类型的方式-scoped enum
scoped enum有以下优点:
- 枚举值的作用域仅会在enum里,避免了名字空间的污染。unscoped enum中的枚举值,其作用域在enum之外
Color r = Color::Red; // 通过Color::作用域来获取枚举值Red Color Red = Color::Red; // 编译通过,因为=号左边的Red与右边的Red不会冲突 Gender g = Male; // 枚举值Male的作用域和Gender的一样,因为Gender属于unscoped enum Gender Male = Male; // 编译失败,因为=号左边的Male与右边的Male冲突了
- 避免了隐式转换,它的默认类型为int。unscoped enum的枚举值类型是不确定的,需要在编译阶段由编译器确定,而且它允许隐式转换
long a = Color::Red; // 编译失败,因为scoped enum不允许编译器偷偷将int类型转换成long类型 long c = Male; // 编译成功,因为Gender属于unscope enum long b = static_cast<int>(Color::Red); // 编译成功,因为用static_cast<int>给Color::Red做了显示转换
- 总是可以前置申明,而要想对unscope enum进行前置申明,则必须对unscope enum指定枚举值的类型。前置申明的好处是减少cpp文件之间的依赖,避免了修改一处源码,而编译多处不必要的cpp文件,进而减少了编译时间
// a.h enum Gender: std::uint8_t; // std::uint8_t指定了Gender枚举值的类型,使得Gender可以前置申明 void Func(Gender g); // a.cpp #include "a.h" #include "m.h" void Func(Gender g){ auto isMale = g == Male; } // m.h enum Gender: std::uint8_t{ Male, Female, Other // 如果增加了Other,编译器不会编译a.cpp,因为a.cpp没有用到Other };#我的求职思考##在找工作求抱抱##我的实习求职记录##C++##C++八股#