C++11学习笔记(3)—— enum

来源:互联网 发布:淘宝的英树是正品吗 编辑:程序博客网 时间:2024/06/16 06:10

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 intswitch( nSelect ){case First:  //enum cast to intcout<<"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;}
OldEnum 和 OldEnum2 都定义了枚举成员 Second,在使用时由于不需要名字的限定,编译器无法知道具体使用哪一个枚举成员,会产生编译错误。


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 identifierstrongEnum1 = 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)不同的枚举变量之间不能互相赋值。

原创粉丝点击