我正在尝试创建一个enum
并执行输出操作符重载以直接打印出这个enum
,但它不起作用。我得到的是以下截图
产生它的代码是:
#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;
}
谁能告诉我这里做错了什么?
答案 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<<
,因为它是更好的匹配。