[cpp] 涓轰肻涔ꢜ蟨骮涔炉air瀵逛躺ostrem髧&# 9860;lt;<杩鞮绗躐,瀵涹ap涓꾏浠ョꢔcopy杩財杈몇?

jinq0123 at 163.com jinq0123 at 163.com
Wed May 9 11:42:40 CST 2007


将operator<<定义在std空间就好了。
namespace std
{
template<class _Elem,class _Traits,class K,class V>
basic_ostream<_Elem,_Traits>& operator<<( ...
...
}

因为名字查找在std找到了operator<<,所以没有看到全局的operator<<.
错误为:no match for 'operator<<'

不可思议:using namespace无效!(1) 
<http://blog.csdn.net/jq0123/archive/2006/07/25/974991.aspx>
是另外一个例子和解释。

张沈鹏(电子科大 大三) wrote:
> 为什么在自定义pair对于ostrem的<<运算符后,对map不可以用copy进行输出?
>
> //copy不能通过编译
> //报错:d:\ungreen\vs2005\vc\include\iterator(308) : error C2679:
> 二进制"<<": 没有找到接受"const std::pair<_Ty1,_Ty2>"类型的右操作数的运 
> 算符(或没有可接受的转换)
>
> //copy(m.begin(), m.end(), ostream_iterator<pair<K,V> >(s, "\n"));
> 改为以下代码就可以通过编译了
> for(map<K,V>::const_iterator i=m.begin();i!=m.end();++i)s<<*i<<"\n";
>
> 下面是完整的源代码
> #include <map>
> #include <string>
> #include <iterator>
> #include <algorithm>
> #include <iostream>
>
> using namespace std;
>
> template<class _Elem,class _Traits,class K,class V>
> basic_ostream<_Elem,_Traits>& operator<<(
>     basic_ostream<_Elem,_Traits>& s
>     ,
>     const pair<K,V>& p
>     )
> {
>     return s<<p.first<<" : "<<p.second;
> }
>
> template<class _Elem,class _Traits,class K,class V>
> basic_ostream<_Elem,_Traits>&  operator<<(
>     basic_ostream<_Elem,_Traits>& s
>     ,
>     const map<K,V>& m
> )
> {
>     //for(map<K,V>::const_iterator 
> i=m.begin();i!=m.end();++i)s<<*i<<"\n";
>     copy(m.begin(), m.end(), ostream_iterator<pair<K,V> >(s, "\n"));
>     return s;
> }
> int main()
> {
>     using namespace std;
>     map<string,string> a;
>     a["key1"]="value1";
>     a["key2"]="value2";
>     cout<<a;
>     system("pause");
>     return 0;
> }
>
>
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>   





More information about the Cpp mailing list