这个错误怎么解决,求助,error C2679: binary '<<'

fancy320 2012-04-18 08:54:32
#include<map>
#include<algorithm>
#include<iterator>
#include<string>
#include<iostream>
using namespace std;
typedef map<string, int> months_type;
template <class First,class Second>
ostream& operator<<(ostream& out,const pair<First,Second> &p)
{
cout<<p->first<<" has "<<p->second<<" days";
return out;
}
ostream& operator<<(ostream& out,const months_type & l)
{
copy(l.begin(),l.end(),ostream_iterator<months_type::value_type>(cout,";"));
return out;
}
void main()
{
months_type months;
typedef months_type::value_type value_type;
months.insert(value_type(string("January"),31));
months.insert(value_type(string("February"),28));
months.insert(value_type(string("April"),30));
months.insert(value_type(string("March"),31));
cout<<months<<endl;

}
//编译时的错误
//error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'const struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class st

...全文
182 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jim_King_2000 2012-04-18
  • 打赏
  • 举报
回复
因为ostream_iterator会寻找operator<<,而std namespace里面有很多operator<<,因此编译器不会去全局空间查找operator<<。也就是说,std::operator<<隐藏了::operator<<。把operator<<放入std namespace即可编译通过。

#include<map>
#include<algorithm>
#include<iterator>
#include<string>
#include<iostream>

using namespace std;

typedef map<string, int> months_type;

namespace std
{
template <class First,class Second>
ostream& operator<<(ostream& out, const pair<First,Second> &p)
{
cout<<p.first<<" has "<<p.second<<" days";
return out;
}

ostream& operator<<(ostream& out,const months_type & l)
{
copy(l.begin(), l.end(), ostream_iterator<months_type::value_type>(out, ";\n"));
return out;
}
}

void main()
{
months_type months;
typedef months_type::value_type value_type;
months.insert(value_type(string("January"),31));
months.insert(value_type(string("February"),28));
months.insert(value_type(string("April"),30));
months.insert(value_type(string("March"),31));
cout<<months<<endl;
}

但是往std namespace里面加东西是不太好的行为,会引起冲突。因此LZ还是不要这样用为好。
taodm 2012-04-18
  • 打赏
  • 举报
回复
cout<<p.first

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧