#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
// 1、枚举类型的定义:
// 普通枚举常量作用域提升至外围(main函数之内)并且可以整型提升
enum Numbers {One=1, Two, Three};
// 强类型枚举常量的作用域仅限于Options类型之内,即{}之内; 并且不进行整型提升
// "One"虽然同名,但由于作用域不同,并不会名字冲突
// 关键字:enum class,位置不能交换
enum class Options {None, One, All=15};
// 2、普通枚举的名字冲突
{
enum Numbers {One, Two, Three};
// enum Options {None, One, All}; // error! 名字冲突:"One"重定义
// int i = One;
}
// 3、枚举常量的整型提升
int i = One; // ok! Numbers's One, i=1
i += Three; // ok!
// i = Options::One; // error! 强类型枚举常量并不能整型提升
i = static_cast<int>(Options::One); // ok! i=1
// 4、枚举变量的定义初始化
Numbers n;
n = One;
n = Numbers::One;
// n += 1; // error!
// n = All; // error! All不在作用域中,并且类型不匹配
// n = Options::One; // error! 试图赋值Options类型的One,类型不匹配
Options o;
// o = One; // error! 试图赋值Numbers类型的One,类型不匹配
// o = All; // error! Options类型之All不在作用域范围
o = Options::One; // ok! 必须使用作用域操作符来访问强类型枚举常量
o = Options::All; // ok!
// 5、在判断语句中的枚举值
if(One<3){} // ok!
if(n==1){} // ok!
if(n<Three){} // ok!
if(One<Three){} // ok!
if(Options::All>Options::One){} // ok! if is true!
if(o==Options::All){} // ok! if is true!
// if(Options::All>10){} // error!
// 6、指定枚举类的底层类型(枚举常量类型),默认时至少为int
enum Enum1: unsigned int{first, second, third};
enum class Enum2: char{first, second, third};
enum Enum3: unsigned int{Red=-6, Blue, Yellow}; // warning C4369: “Red”: 枚举数的值“-6”不能表示为“unsigned int”,值是“4294967290”
std::cout << Red << std::endl;
enum class Enum4: char{first=10086, second, third}; // warning C4369: “first”: 枚举数的值“10086”不能表示为“char”,值是“102”
// std::cout << Enum4::second << std::endl; // error! 强类型枚举Enum4没有此操作,second不是整型
std::cout << (char)Enum4::second << std::endl;
// enum class Enum4: double{Red=-6, Blue, Yellow}; //error:!“double”: 枚举的基础类型非法,不是整型
return 0;
}
【c++11】 enum class: 强类型枚举
最新推荐文章于 2024-04-15 20:08:10 发布