C/C++ enum class(C++11),enum枚举
枚举是c++的一种机制,用来列出某种有穷集合。在C++11中新增了enum class(同enum struct),那它跟enum有何不同呢?
enum的特点:
enum的成员初始化,如果已被指定就按指定值初始化。如果没有被指定,那么就是上一个成员值加1,第一个成员没有指定则为0。
- 向整形的隐式转换。
- 作用域的问题,如果已经有一个枚举类中的成员名称被占用,那么它无法再被定义。
- 不清楚底层类型,这个在不同的编译器上可能是不同的类型。
举个例子:
#include <iostream> using namespace std; enum color { red, yellow = 4, blue = 0xFFFFFF00U }; enum mycolor { //red, //不可以定义,由于在color中已被定义 white, pink }; void func(int c) { cout<<"call func "<<endl; } int main() { color c(red);//red作用域可见 func(c);//发生转换,enum color转int cout<< red << endl; cout<< yellow << endl; cout<< blue << endl; return 0; }
以上输出结果为:
call func 0 4 4294967040
也可能为
call func 0 4 -1
由于枚举底层数据类型没有规定,不同编译器有不同结果。
而针对enum的一些问题。enum就能很好的解决它。
enum class的特点:
- 与整形间不会发生类型转换。
- 作用域的问题,需要通过域运算符访问。
- 默认的底层数据类型是int。
举个例子:
#include <iostream> using namespace std; enum class color{ red, yellow, blue }; void fun_int(int x) { cout<<"fun int: "<<x<<endl; } int main() { color c(static_cast<color>(1)); //error //fun_int(c); fun_int(static_cast<int>(c)); fun_int(static_cast<int>(color::red)); //error //fun_int(static_cast<int>(red)); return 0; }
结果是:
fun int: 1 fun int: 0
如果声明 enum class color:int 会报错:
192:~ lurongming$ g++ main.cc main.cc:26:6: warning: scoped enumerations are a C++11 extension [-Wc++11-extensions] enum class color:int{ ^ main.cc:26:12: error: ISO C++ forbids forward references to enum types enum class color:int{ ^ main.cc:26:17: error: expected unqualified-id enum class color:int{ ^ main.cc:45:27: warning: use of enumeration in a nested name specifier is a C++11 extension [-Wc++11-extensions] fun_int(static_cast<int>(color::red)); ^ main.cc:45:27: error: incomplete type color named in nested name specifier fun_int(static_cast<int>(color::red)); ^~~~~~~ 2 warnings and 3 errors generated.
ISO C++ forbids forward references to ‘enum’ types enum 禁止指定类型。
下一篇:
python数据分析之读写txt文件