enum class 是C++中一种强大的类型安全枚举方式,它通过引入作用域限制和类型安全机制,显著提升了代码的安全性和清晰度。正确使用enum class不仅可以避免命名冲突和类型混淆,还能使代码更加易于理解和维护。掌握其常见问题和易错点,结合高效使用技巧,能够帮助开发者编写出更高质量的C++代码。在实际应用中,应根据具体需求灵...
1) C++98 的 enum 是“非域化的”;而 C++11 的 enum class 是“域化的”,限制了枚举成员只在域内可见 2) enum class 的缺省潜在类型 (underlying type) 是 int 型,而 enum 没有缺省潜在类型 3) enum class 一般总是前置声明,而 enum 只有在指定了潜在类型时才可以是前置声明 参考资料 《Effective Mod...
枚举类的底层数据必须是有符号或无符号整型,比如 char unsigned int unsigned long,默认为 int。 3.前置声明应用 enmu class Clolor:char; //前置声明枚举类 void Foo(Color*p); //前置声明的使用 //... enum class Color:char{RED,GREEN,BLACK,WHITE}; //前置声明的定义 参考:http://blog.csdn.net...
enum class..enum class转整型最安全的做法就是使用std::to_underlying,虽然这玩意C++23才有,但自己写一个也是很简单的。就你期望的用法而言,可以参考标准库future中std::lau
简介: C/C++ - enum 与 int 相互转换 First of all——如何正确理解enum类型? enumColor { red, white, blue}; Colorx; 我们应说x是Color类型的,而不应将x理解成enumeration类型,更不应将其理解成int类型。 我们再看enumeration类型: enumColor { red, white, blue}; 理解此类型的最好的方法是将这个...
enum class Sex { Girl, Boy }; enum class Student { Girl, Boy }; int main(int argc, char *argv[]) { Sex a = Sex::Gril; Student b = Student::Gril; //两者处于不同作用域下,不会重定义 } 二.枚举类型enum的使用 定义: enum /*枚举类型*/ ...
enum class Status; // use of fwd-declared enum void continueProcessing(Status s); 2) 潜在类型enum class 的潜在类型 (underlying type),缺省为 int 型,当然也可自定义潜在类型。无论哪种方式,编译器都会预先知道枚举成员的大小1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // underlying type...
class IntTestA(enum.IntEnum): A = 1 B = 2 print(['a', 'b', 'c'][IntTestA.A]) # 枚举成员作为索引 # b print([i for i in range(IntTestA.B)]) # 枚举成员作为 range() 函数的参数 # [0, 1] Flag Flag类是Enum类的子类,Flag类与Enum类的差别就是Flag枚举成员可以使用按位运算符(...
enum class E2 { A = 1, C = 2 };// 1. 强枚举类型不会将枚举元素暴露在外部作用域 cout << (int)(E1::A) << endl;int A = 100;// 2. 不相关的两个枚举类型不能直接比较,编译报错 cout << (E1::B == E2::C ? "相等" : "不相等") << endl; //error cout << (E1::B ==...
enum class colorx{red,green=100,yellow}; //... 2.3 类型转换 与整形之间不会发生隐式类型转换,但是可以强转。 #include <iostream> enum class color { red, green, yellow}; int main() { //int res(color::red); //ERROR , “初始化”: 无法从“color”转换为“int” //color col(2);//...