2015-10-06 43 views
0

我对C++编程相当陌生。我现在有一个 错误C2678:二进制“==”:没有操作员发现这需要类型“常量员工”如何创建一个合适的bool Employee :: operator ==(const Employee&rhs)const

的左手操作此错误是点到线

if (*iLoc == aID) 

我相信我我想创建一个

bool Employee::operator==(const Employee & rhs) const 
{ 
} 

将覆盖该错误。我认为我需要制作一个超载的==运营商,能够比较unsigned intEmployee对象。但我被卡住了。我想知道是否有人能够提供帮助。包括我的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

在功能void removeItem(List<Employee>&),在线路

if (*iLoc == aID) 

您比较一个解除引用的迭代器,即一个Employee,到unsigned intaID)。右侧必须是Employee,或者Employee必须有一个隐含的构造函数,它将unsigned int作为参数,因此编译器在尝试解析(*iLoc).operator==(aID)时可能会将aID转换为Employee(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

+0

你的意思是这样的吗? bool Employee :: operator ==(const Employee&rhs)const { \t return(ID == rhs.ID); } – OrangePineapple

+0

@OrangePineapple你应该写一些类似'return rhs.aID == aID'的东西。尝试找到一些好的书籍/教程。 – vsoftco

+0

我试过在网上看,看了一些教科书。仍然没有任何地方。 – OrangePineapple

相关问题