【发布时间】:2015-06-29 15:23:56
【问题描述】:
我想将枚举值打印为文本并用于重载。假设我有以下代码:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>
enum enm{
One,
Two
};
class Complex{
public:
friend std::ostream& operator<<(std::ostream& out, std::unordered_multiset<int>::const_iterator i){
switch (*i){
case One:{
return out<<"One";
}
case Two:{
return out << "Two";
}
}
}
void func(std::unordered_multiset<int> _v);
};
void Complex:: func(std::unordered_multiset<int> _v){
_v.insert(One);
_v.insert(Two);
for (std::unordered_multiset<int>::const_iterator i(_v.begin()), end(_v.end()); i != end; ++i){
std::cout <<"Num: " << *i <<std::endl; //need to get here "One", "Two" instead of 0, 1
}
}
int main(){
Complex c;
std::unordered_multiset<int> ms;
c.func(ms);
return 0;
}
问题是这个变体不起作用。所以,我得到 0, 1 而不是 One, Two。不知道如何正确地做到这一点。 谢谢你的帮助!
【问题讨论】:
-
附带说明:不要使用
_作为变量前缀,这是为 c++ 实现内部保留的。
标签: c++ c++11 stl operator-overloading