我有一个像下面的对象
class MyClass{
int a;
double b;
};
和
vector<MyClass> vMyClass;
然后我想在vMyClass中搜索尝试使用算法函数:
if( std::find(vMyClass.begin(), vMyClass.end(), aiField) == vMyClass.end())
我还定义了operator==
int operator ==(Field &Left,Field &Right)
{
return memcmp(&Left,&Right,sizeof(Field));
}
或
int operator ==(Field &Right)
{
return memcmp(this,&Right,sizeof(Field));
}
但是收到错误消息。
1>c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\algorithm(40) : error C2678: binary '==' : no operator found which takes a left-hand operand of type 'MyClass' (or there is no acceptable conversion)
1> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\guiddef.h(192): could be 'int operator ==(const GUID &,const GUID &)' [found using argument-dependent lookup]
1> c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(85): or 'int operator ==(MyClass &,MyClass &)' [found using argument-dependent lookup]
1> c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(70): or 'int MyClass::operator ==(MyClass &)'
1> while trying to match the argument list '(MyClass, const MyClass)'
1> c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\algorithm(74) : see reference to function template instantiation '_InIt std::_Find<std::_Vector_iterator<_Ty,_Alloc>,_Ty>(_InIt,_InIt,const _Ty &)' being compiled
1> with
1> [
1> _InIt=std::_Vector_iterator<MyClass,std::allocator<MyClass>>,
1> _Ty=MyClass,
1> _Alloc=std::allocator<MyClass>
1> ]
1> c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(108) : see reference to function template instantiation '_InIt std::find<std::_Vector_iterator<_Ty,_Alloc>,MyClass>(_InIt,_InIt,const _Ty &)' being compiled
1> with
1> [
1> _InIt=std::_Vector_iterator<MyClass,std::allocator<MyClass>>,
1> _Ty=MyClass,
1> _Alloc=std::allocator<MyClass>
1> ]
1>CommandArgParser.cpp
1>Generating Code...
答案 0 :(得分:14)
它们需要是const引用。 memcmp
真的非常非常糟糕 - 只是进行成员比较。
答案 1 :(得分:7)
您忘记了const
运算符中的==
限定符,而且它应该返回bool
,而不是int
。只需使用它:
bool operator ==(const Field &Left, const Field &Right)
{
return (Left.a == Right.a) && (Left.b == Right.b);
}
答案 2 :(得分:1)
你有一个MyClass
的向量,但是Field
的比较运算符。你必须写一个
bool operator == (const MyClass &, const MyClass &)
。
此运算符应(如其他人所示)不使用memcmp
,而是执行成员比较。
答案 3 :(得分:1)
在类本身中实现运算符:
class MyClass
{
public:
int a;
double b;
bool operator ==(const MyClass &Right) const
{
return (a == Right.a) && (b == Right.b); // 'this' is left
}
};