cout
无作用域枚举直接工作:
#include <iostream>
using namespace std;
enum color { red, green, blue };
int main()
{
cout << color::green;
return 0;
}
虽然使用socoped枚举不能:
#include <iostream>
using namespace std;
enum class color { red, green, blue };
int main()
{
cout << color::green;
return 0;
}
有什么区别?
这是有效的,因为无作用域枚举可以隐式转换为整数,而作用域枚举不能,并且需要显式转换:
cout << static_cast<int>(color::green);
无作用域枚举会自动转换为某个整数类型。这就是为什么它只会打印出1
,而不是green
.
作用域枚举不能隐式转换为整数,并且没有其他operator<<
用于std::cout
,因此无法编译。
也许像 char 这样的最佳属性可以帮助你。
#include <iostream>
using namespace std;
enum class Color { red='r', green='g', blue='b' };
int main()
{
cout << "Print opt attribute: " << static_cast<char>(Color::green);
return 0;
}
在线测试 :
https://onlinegdb.com/Syw-qgg97