views:

231

answers:

1

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

+5  A: 

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.

Evan Teran
Edit show what I have now. Error still thereThe reason for two methods is so I can pass by reference or by value. I just placed return true in there for testing purposes.Thanks for the help.
Jeremiah
Why do you wish to pass by value? The only useful things to pass should be allowed by the const ref version.
Evan Teran
Yours works for me in a new project, but not in my current one. I'm going to go thru and see what I can find. I'll post back in a bit with the results. Thanks
Jeremiah
I went back and rewrote my main. Works now.Thanks for all the quick help.
Jeremiah