为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
Why can't cout a scoped enum class member directly while can for unscoped enum?
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
相关文章:
- 枚举成员与静态 int 成员?
- 从类访问枚举成员
- 枚举成员不是类型错误
- std::映射键作为模板化结构与枚举成员
- 设置类的枚举成员无效地使用"枚举"
- 如何访问结构和枚举成员形成一类
- 是否可以在 constexpr 函数中遍历枚举成员,因此值为 constexpr
- 获取 [枚举成员?] 的封闭类型
- 如何使用 SWIG 枚举枚举成员
- 通过int值访问枚举成员
- '='应初始化所有枚举成员或仅初始化第一个枚举成员;
- 为什么可以获取此枚举成员值,而不必先深入研究嵌套枚举
- 将具有枚举成员的非托管结构封送到 C#
- 为类模板的枚举成员定义 std::hash
- 缩短C++枚举成员的路径(使用 typedef 或 typename),以用作模板参数
- C++类枚举成员变量
- 检查是否已定义枚举成员
- 为什么要使用这段代码来获取枚举成员的数量?
- 使用枚举成员模板化成员函数
- 使用咬运算符了解枚举成员的初始化