【发布时间】:2012-11-17 06:09:48
【问题描述】:
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 也会为操作员生成 ==
如何解决这个问题?
更具体地说,错误导致:
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);
}
};
关于功能
最终案例:
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 );
}
【问题讨论】:
-
函数体后面的分号不应该存在。
-
@chris:它们是不必要的,但 C++ 确实允许它们(显然因为很多人确实这样做了,并且允许它们几乎没有损失)。
-
@JerryCoffin,确实,虽然我相信
-pedantic会得到它们。他们只是在我看来很奇怪。