重载操作符在使用std :: map时会产生错误 [英] Overloaded operator generates errors when using std::map
本文介绍了重载操作符在使用std :: map时会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A
{
private:
int a;
public:
A( int set )
{
a = set;
};
~A();
bool operator <(const A& ref )
{
return this->a < ref.a;
};
bool operator ==(const A& ref )
{
return this->a == ref.a;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
map<A,int>m;
A a( 1 );
m.insert( make_pair( a, 2 ) );
for( map<A,int>::iterator it = m.begin(); it != m.end(); ++it )
{
}
return 0;
}
生成C2678: http://msdn.microsoft.com/en-us/library/ys0bw32s(v = vs.80)。 aspx
如果我使用 m.find
也会为操作符生成==
如何获取
and if I use m.find
will also generate for the operator ==
How to get around with this?
更具体地说,错误会导致:
To be more specific the error leads to:
template<class _Ty>
struct less
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
功能
/ p>
Final case:
struct MASTERPLAYER
{
int a;
bool operator==( const MASTERPLAYER& ref ) const
{
return a == ref.a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
MASTERPLAYER m;
vector<MASTERPLAYER>v;
v.push_back( m );
std::find( v.begin(), v.end(), 2 );
}
推荐答案
您要将函数标记为 const
,表示它们不修改调用它们的对象:
You want to mark the functions as const
, to signify that they don't modify the object on which they're invoked:
bool operator <(const A& ref ) const
{
return a < ref.a;
};
bool operator ==(const A& ref ) const
{
return a == ref.a;
};
这篇关于重载操作符在使用std :: map时会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文