首页 > 解决方案 > 二进制“<<”:未找到采用“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)。

标签: c++

解决方案


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;

}

演示


推荐阅读