重载运算符<<对于枚举导致重复输出

时间:2016-02-01 20:32:02

标签: c++ enums operator-overloading

我正在尝试创建一个enum并执行输出操作符重载以直接打印出这个enum,但它不起作用。我得到的是以下截图

enter image description here

产生它的代码是:

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;

enum KeyboardLayout
{
 arabic, chinese, english, french, german
};

ostream& operator<<(ostream& out, KeyboardLayout& k)
{
  out<<"(keyboard layout: "<< k << ")"<<endl;

  return out;
}

int main()
{

KeyboardLayout k=english;

cout<<k;


return 0;
}

谁能告诉我这里做错了什么?

2 个答案:

答案 0 :(得分:3)

你有一个无限递归

cout<<k;

调用ostream& operator<<(ostream& out, KeyboardLayout& k)。那你有

out<<"(keyboard layout: "<< k << ")"<<endl;

在重新调用ostream& operator<<(ostream& out, KeyboardLayout& k)的函数中。如你所见,这将永远不会结束。

您需要有一个switch语句或if块,具体取决于k打印出的字符串是否与其保存的值相同。像这样:

ostream& operator<<(ostream& out, KeyboardLayout& k)
{
  out<<"(keyboard layout: ";

  switch(k)
  {
    case arabic: out << "arabic"; break;
    case chinese: out << "chinese"; break;
    case english: out << "english"; break;
    case french: out << "french"; break;
    case german: out << "german"; break;
  }

  out << ")"<<endl;

  return out;
}

答案 1 :(得分:2)

@NathanOliver's answer完全正确。我的回答是一个快速而又脏的修复:在调用k时在operator<<上执行强制转换:

out<<"(keyboard layout: "<< static_cast<int>(k) << ")"<<endl;

净效应将是编译器将调用泛型operator<<,因为它是更好的匹配。

Live on Coliru