C++11——5.9 强类型枚举

发布时间 2023-08-27 22:37:41作者: 我会变强的

详细介绍请见:★★★原文链接★★★:https://subingwen.cn/cpp/enum/

 

枚举语法(C++98):

关键字enum  枚举名字(可以不写,不写就是匿名枚举)  {枚举值};

#include <iostream>
using namespace std;

// 枚举在相同作用域内全局范围内可见(定义在类内 就类内全局可见;定义在全局 就全局可见)
// 因此相同的枚举值只能有 1 个(即使枚举名字不同(花括号前面的名字),但是枚举值(花括号里)相同也不行)
// enum { Red, Green, Blue };
enum Color { Red, Green, Blue };

int main() {
	cout << "red:" << Red << endl;
	cout << "green:" << Green << endl;
	cout << "blue:" << Blue << endl;
	return 0;
}

res:

  

在枚举类型中的枚举值编译器会默认从0开始赋值,而后依次递增。

 

强类型枚举语法:

关键字enum  关键字class或struct(都一样)  枚举名字(如果指定底层类型(默认为int),这里应该是 枚举名字:指定类型 )  {枚举值};

#include <iostream>
using namespace std;

enum class Color { Red, Green, Blue };	// ★★★枚举值的类型默认为int型
enum class Color2 :char { Red, Green, Blue };	// 将枚举值的类型变为char类型

enum TestColor :char { Red = 'a', Green, Blue };	// ★★★普通枚举

int main() {
	// cout << "red:" << Red << endl;	// ★★★报错;强类型枚举值的访问必须加上枚举名字
	// cout << "red:" << Color::Red << endl;	// ★★★还是报错;虽然强类型枚举的底层默认类型为int,但是强类型枚举成员值不能进行隐式转换,要显示转换
	cout << "red:" << (int)Color::Red << endl;

	cout << "Color size:" << sizeof(Color::Red) << endl;
	cout << "Color2 size:" << sizeof(Color2::Red) << endl;

	// ★★★C++11对原有枚举进行了扩展
	// 1. 可以加作用域访问(当然也可以不加)
	// 2. 可以对底层枚举值的类型进行修改(枚举名字后加":"和"类型")
	cout << "TestColor red:" << Red << endl;	// ★★★普通枚举会自动进行类型转换(强类型枚举不会)
	cout << "TestColor green:" << TestColor::Green << endl;
	return 0;
}

res:

  

★★★原文链接★★★:https://subingwen.cn/cpp/enum/

(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)