【问题标题】:Why does trying to print enum class in c++ give an error? [duplicate]为什么尝试在 C++ 中打印枚举类会出错? [复制]
【发布时间】:2020-12-17 14:07:48
【问题描述】:

我想打印以km为单位的你

enum class Unit { km, m, cm };

int main()
{
Unit u = Unit::km; 
std::cout<<u; 
return 0; 
}

为什么会出错?

错误:

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Unit’)

【问题讨论】:

  • 当您对编译代码时收到的错误有疑问时,始终包含逐字错误消息。应该是included in your question
  • 当我运行它时,我得到error: ‘cout’ was not declared in this scope 所以我认为是这样?

标签: c++


【解决方案1】:

您的Unit 枚举是一个作用域枚举,enum class,这些类型的枚举不允许隐式转换。如果您希望它与 cout 一起使用,则必须显式转换:

std::cout << static_cast<int>(u);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
相关资源
最近更新 更多