No match for 'operator==' C++ compile error

南笙酒味 提交于 2020-05-23 12:37:52

问题


Another question from a C++ newbie.

I'm receiving a compiler error "No match for 'operator=='" for the following block of code

void swap(Team t1, Player p1, Team t2, Player p2){
    Player new_t1[11];
    Player new_t2[11];
    for(int i=0; i<11; i++){
        new_t1[i] = t1.get_player(i);
        new_t2[i] = t2.get_player(i);
        if(new_t1[i] == p1){
            new_t1[i] = p2;
        }
        if(new_t2[i] == p2){
            new_t2[i] = p1;
        }
    }

    cout << "Players swapped.";
}

Any ideas?


回答1:


The compiler doesn't know what it means for the two players to be the same. Are they the same if their names are the same? Or their IDs? You need to define == operator for class Player.

bool operator == (const Player &p1, const Player &p2)
{
   if( / * evaluate their equality */)
     return true;
   else
     return false;
}

Also, I don't think your swap() function has any effect right now. You may want to change it to accept Teams and Players by reference.




回答2:


You need to "overload" the == operator for your Player class. In other you need to tell the compiler what to compare within your Player object.

Example :

bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. }

Might help you : Operator Overload

Regards, Erwald




回答3:


The problem is here:

if(new_t1[i] == p1){

The compiler doesn't know how to compare two Player objects, unless you explicitly tell it by implementing operator==. See the "Comparison operators" section of this guide.



来源:https://stackoverflow.com/questions/10149059/no-match-for-operator-c-compile-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!