简体   繁体   中英

c++ overload operator==

I have a class with the following

bool DistinctWord::operator==(const DistinctWord W) const
{
    return strWord == W.strWord;
}
bool DistinctWord::operator==(const DistinctWord& W) const 
{
    return strWord == W.strWord;
}

I'm doing this in my program

    DistinctWord* wordOne = new DistinctWord("Test");
    DistinctWord* wordTwo = new DistinctWord("Test");

    if(*wordOne == *wordTwo)
        cout << "true";
    else
        cout << "false";

I get this error

error C2678: binary '==' : no operator found which takes a left-hand operand of type 'DistinctWord' (or there is no acceptable conversion) could be 'built-in C++ operator==(DistinctWord *, DistinctWord *

)'

I'm probably just not understanding the right way to overload.

Sorry for the simple question. TIA

EDIT:

OK, I've figured out your problem. It is the non-reference version of the operator== . It makes the operator== ambiguous. Simply remove it (as I originally suggested) and it'll work fine.


EDIT:

In response to your edit, you should still remove the first version of the operator== There is no need to make a copy of the object in question and then compare it. The second operator== looks reasonable and should work. Is there anything else you are leaving out?


EDIT:

The following compiles just fine for me using g++ 4.4.1:

#include <iostream>

struct DistinctWord {
    DistinctWord(const std::string &s) : strWord(s){}

    bool operator==(const DistinctWord& W) const {
        return strWord == W.strWord;
    }

    std::string strWord;
};


int main() {
    DistinctWord* wordOne = new DistinctWord("Test");
    DistinctWord* wordTwo = new DistinctWord("Test");

    if(*wordOne == *wordTwo)
        std::cout << "true";
    else
        std::cout << "false";
}

If you are still having problems, then you are not showing all relevant code...


First of all, where is the definition for DistinctWord and how does it relate to Word ?

Beyond that, you should do this:

bool Word::operator==(const Word& W) const {
     return strWord == W.strWord;
}

and just remove the two operator== 's you currently have. The first is making a copy then comparing which is silly, and your second is comparing a modifiable reference and always returning true which doesn't really serve any purpose.

This one should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM