1.简介
以往的enum类型将枚举成员的作用域暴露在枚举变量之外,用户不需要指定枚举类型就可以直接使用枚举的内容,这就有可能会造成名字的冲突,为了解决该你问题,C++11引入了强类型的枚举类型(strongly typed enums ).
2.旧风格的enum
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- enum OldEnum
- {
- First,
- Second,
- Third,
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- int nSelect = Second; //enum cast to int
- switch( nSelect )
- {
- case First: //enum cast to int
- cout<<"Select first"<<endl;
- break;
- case Second:
- cout<<"Select second"<<endl;
- break;
- case OldEnum::Third: //也支持通过enum限定
- cout<<"Select third"<<endl;
- break;
- default:
- cout<<"Select none"<<endl;
- break;
- }
- system("pause");
- return 0;
- }
由上述示例可以看出,旧风格的enum数据类型支持直接对enum成员的使用,例如First 同时也支持通过enum 名字的限定,例如,OldEnum::Third. 但后者不是强制的要求。旧风格的enum会自动根据需求转换成整数类型。
由于没有强制性的名字限定的要求,容易造成枚举类型名字的冲突,例如:
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- enum OldEnum
- {
- First,
- Second,
- Third,
- };
- enum OldEnum2
- {
- MyFirst = 1,
- Second,
- My_Third,
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- int nSelect = Second; //error C2365: 'Second' : redefinition; previous definition was 'enumerator'
- system("pause");
- return 0;
- }
3.强类型enum(C++11)
强类型enum数据类型在定义时和旧风格不同,需要添加 class 关键字。
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- enum class StrongTypeEnum
- {
- First,
- Second,
- Third,
- };
- enum class StrongTypeEnum2
- {
- MyFirst = 1,
- Second,
- My_Third,
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- StrongTypeEnum strongEnum1;
- strongEnum1 = StrongTypeEnum::First; // OK
- //error C2065: 'First' : undeclared identifier
- strongEnum1 = First;
- //error C2440: 'initializing' : cannot convert from 'StrongTypeEnum' to 'int'
- int nStrong = StrongTypeEnum::Second;
- StrongTypeEnum2 strongEnum2;
- //error C2440: '=' : cannot convert from 'StrongTypeEnum' to 'StrongTypeEnum2'
- strongEnum2 = StrongTypeEnum::First;
- switch (strongEnum1)
- {
- case StrongTypeEnum::First:
- break;
- case StrongTypeEnum::Second:
- break;
- case StrongTypeEnum::Third:
- break;
- default:
- break;
- }
- system("pause");
- return 0;
- }
(1)使用enum class 进行定义
(2)避免了名字冲突,StrongTypeEnum 和 StrongTypeEnum2都定义了成员 Second,但是由于各属于各自的空间,不会造成名字冲突
(3)使用枚举成员必须通过名字的限定
(4)枚举变量不能转换为整型
(5)不同的枚举变量之间不能互相赋值。
转载自http://blog.youkuaiyun.com/fire_lord/article/details/8531594