c++ - 二进制“<<”:未找到采用“c1”类型的右侧操作数的运算符
问题描述
我正在用 C++ 进行试验,然后我偶然发现了这个问题:- 二进制“<<”:没有找到采用“c1”类型的右手操作数的运算符
是什么导致了这样的问题?
using c1 = enum class Color : unsigned int {
red,
green,
blue,
};
int main()
{
c1 col{ Color::red };
std::cout << "Value of col is " << col;
}
当我使用enum后仅使用名称Color时,它会提示警告:-
枚举类型“颜色”是无范围的。更喜欢“枚举类”而不是“枚举”(Enum.3)。
解决方案
unsigned int
如果您想打印该值,您可以将其转换为。如果你想打印字符串,那么你必须为此编写一个函数,如下所示:
#include <string> // For std::string
#include <iostream>
using c1 = enum class Color : unsigned int {
red,
green,
blue,
};
inline std::string ColorToString(c1 color)
{
switch (color)
{
case c1::red: return "red";
case c1::green: return "green";
case c1::blue: return "blue";
}
return "";
}
int main()
{
c1 col{ Color::red };
// If you are trying to output the name of the enum
std::cout << "Name of col is " << ColorToString(col) << std::endl;
// If you are trying to output the value of the enum
std::cout << "Value of col is " << static_cast<unsigned int>(col) << std::endl;
}
推荐阅读
- r - 基于单独列中的两个因子水平的行值差异的 Dplyr 解决方案
- php - PHP - 如何查看某个单词是否在特定网页上?
- javascript - ag-grid 更改类或将样式更改为 RowNode
- sqlite - 在选择内插入触发器
- java - Spring,当我使用`saveAll`时有很多SQL请求
- python-3.x - 如何根据另一列计算数据框中的常见元素
- javascript - php 没有收到来自 ajax 类型帖子的任何请求,是否需要在邮件中提及用户名和密码
- ios - 我正在使用 Xcode10.1,但它意外崩溃
- flutter - 为什么可拖动的容器在拖动时没有圆角?
- javascript - 过滤其中包含另一个数组的数组