'operator==' C++ 编译错误不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10149059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:39:52  来源:igfitidea点击:

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

c++compiler-errors

提问by user1332364

Another question from a C++ newbie.

来自 C++ 新手的另一个问题。

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

我收到以下代码块的编译器错误“No match for 'operator=='”

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?

有任何想法吗?

回答by George Skoptsov

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.

编译器不知道两个玩家相同意味着什么。如果它们的名字相同,它们是否相同?还是他们的身?您需要为 定义 == 运算符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.

另外,我认为您的swap()功能现在没有任何影响。您可能希望将其更改为通过引用接受Teams 和Players。

回答by Erwald

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.

您需要为 Player 类“重载” == 运算符。在其他情况下,您需要告诉编译器在您的 Player 对象中比较什么。

Example :

例子 :

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

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

Might help you : Operator Overload

可能对您有所帮助:运算符重载

Regards, Erwald

问候, 埃尔瓦尔德

回答by Graham Borland

The problem is here:

问题在这里:

if(new_t1[i] == p1){

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

编译器不知道如何比较两个Player对象,除非您通过实现operator==. 请参阅本指南的“比较运算符”部分。