我是C ++编程的新手。我现在有一个 错误C2678:二进制'==':找不到哪个运算符带有'const Employee'类型的左操作数
此错误指向行
if (*iLoc == aID)
我相信我想创建一个
bool Employee::operator==(const Employee & rhs) const
{
}
将覆盖错误。我想我需要制作一个能够与==
unsigned int
对象进行比较的重载Employee
运算符。但我被卡住了。我想知道是否有人能够提供帮助。我的main.cpp的一部分包括在内。
bool Employee::operator==(const Employee & rhs) const
{
}
void searchItem(const List<Employee>& l1)
{
if (l1.size() == 0)
cout << "List empty!\n";
else
{
unsigned int ID;
cout << "Enter ID#: ";
cin >> ID;
size_t index = 0;
List<Employee>::const_iterator iLoc = l1.begin();
while (iLoc != l1.end())
{
if (*iLoc == aID)
{
cout << "Employee's Name: " << aID << " found at node # " << index << endl;
break;
}
index++;
iLoc++;
}
if (iLoc == l1.end())
cout << "ID# " << aID << " not found!\n";
}
}
void removeItem(List<Employee>& l1)
{
if (l1.size() == 0)
cout << "List empty!\n";
else
{
unsigned int aID;
cout << "Enter ID#: ";
cin >> aID;
size_t index = 0;
List<Employee>::iterator iLoc = l1.begin();
while (iLoc != l1.end())
{
if (*iLoc == aID)
{
cout << "Value " << aID << " removed from node # " << index << endl;
l1.erase(iLoc);
break;
}
index++;
iLoc++;
}
if (iLoc == l1.end())
cout << "Value not found!\n";
}
}
答案 0 :(得分:0)
在函数void removeItem(List<Employee>&)
中,在行
if (*iLoc == aID)
您正在将解除引用的迭代器(即Employee
)与unsigned int
(aID
)进行比较。右侧也必须是Employee
,或者Employee
必须有一个隐式构造函数,它将unsigned int
作为参数,因此编译器可能能够转换aID
尝试解决对Employee(aID)
的调用时(*iLoc).operator==(aID)
。
解决方案:定义
bool Employee::operator==(const Employee & rhs) const
{
return comparison_here;
}
并确保Employee
的构造函数带有unsigned int
,或者创建一个带operator==
的重载unsigned int
,
bool Employee::operator==(unsigned int rhs) const
{
return comparison_here;
}
您也可以考虑将operator==
定义为非成员函数,因此它也可以将unsigned int
作为左侧参数。更多详情:Operator overloading