c++ - 使用 ostream 和枚举类型重载 <<

标签 c++ oop enums operator-overloading

以下是我的代码。我正在尝试打印一个枚举数据类型变量,一个直接显示其名称,另一个带有返回与原始变量相同数据类型的函数。

#include <iostream>

using namespace std;
enum days{SUN, MON, TUE, WED, THU, FRI, SAT};


inline days dayaftertomorrow(days d)
{
  return static_cast<days>((static_cast<int>(d) + 2) % 7);
}

ostream& operator<< (ostream& out, days& day)
{
  switch(day)
  {
    case SUN: out << "SUN"; break;
    case MON: out << "MON"; break;
    case TUE: out << "TUE"; break;
    case WED: out << "WED"; break;
    case THU: out << "THU"; break;
    case FRI: out << "FRI"; break;
    case SAT: out << "SAT"; break;
  }
  return out;
}


int main(int argc, char const *argv[]) {
  days d = MON, e;
  e = dayaftertomorrow(d);
  cout << d << "\t" << e << endl;
  cout << d << "\t" << dayaftertomorrow(d) << endl;
  return 0;
}

我期望的结果是

MON     WED
MON     WED

但是我得到了

MON     WED
MON     3

我该如何解决这个问题?

最佳答案

请注意 operator<<正在采用参数 day通过引用非常量。 dayaftertomorrow按值(value)返回;什么dayaftertomorrow returns 是一个临时变量,不能绑定(bind)到对非常量的引用。然后为 cout << dayaftertomorrow(d) , 你的 operator<<不会被调用,枚举器将为 implicitly convertedint然后通过 std::basic_ostream::operator<< 打印出来反而;这就是为什么你得到 3 .

要解决此问题,您可以将参数类型更改为对 const 的引用;可以绑定(bind)到临时的。或者改成传值。例如

ostream& operator<< (ostream& out, const days& day)
//                                 ~~~~~

ostream& operator<< (ostream& out, days day)

LIVE

关于c++ - 使用 ostream 和枚举类型重载 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794504/

相关文章:

matlab - 当对象的方法之一用作其自身属性的回调时,如何调用对象的析构函数?

c# - 枚举名称的优先级

java - Scala 枚举可以像 Java 一样映射到整数吗?

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 在 C++ 代码中集成 matlab C++ 共享库

java - 构造函数中可覆盖的方法调用有什么问题?

java - 让通用 AsyncTask 处理任何异常

c++ - 静态 constexpr 成员似乎不支持 std::min

c++ - C++ 类 UnsatisfieldLinkError 的 JNI

c++ - 前向声明类枚举问题的解决方法?