Juarrow
Juarrow

Reputation: 2414

overloading operators == and != : compiler moans ambiguity

I have the following code:

bool operator==(const Inc::CReminderItem& Item1, const Inc::CReminderItem& Item2)
{
    bool bDate = false, bDesc = false, bInfo = false, bWeekday = false;

    if(Item1.m_Date == Item2.m_Date)
        bDate = true;
    if(Item1.m_strDescription == Item2.m_strDescription)
        bDesc = true;
    if(Item1.m_strInfoShort == Item2.m_strInfoShort)
        bInfo = true;
    if(Item1.m_nWeekday == Item2.m_nWeekday)
        bWeekday = true;

    return(bDate && bDesc && bInfo && bWeekday);
}

bool operator!=(const Inc::CReminderItem& Item1, const Inc::CReminderItem& Item2)
{
    return !(Item1 == Item2);    // <<--- ambiguous here!
}

both operators are declared as friend operators in the class.

the error is:

error C2593: 'operator ==' is ambiguous

I am not sure, why it is ambiguous O_o and how to fix this. Any help is greatly appreciated:)

Upvotes: 0

Views: 231

Answers (2)

James Kanze
James Kanze

Reputation: 154047

First, if it is "ambiguous", I would expect other operator== to be present somewhere. But it's hard to say what any particular compiler is really trying to tell you with it's error messages.

Second, you really don't show enough code for anyone to say what is wrong. There are a number of possible errors: the class where the friend is declared and these definitions are in different namespaces, the signature of the friend is subtly different, etc. If Inc is a namespace, these operators must be in Inc as well. Otherwise, you've declared an operator== in Inc in the friend declaration, and an operator== in global namespace here. Both are considered, which results in an ambiguity.

(The way I usually handle this is to define a member function, isEqual, and have both operator== and operator!= call it. That way, there's no need for the friend declaration.)

Upvotes: 2

neuront
neuront

Reputation: 9622

Maybe you have defined a operator== within the class scope like

class CReminderItem {
public:
    bool operator==(CReminderItem const&) const;
};

That is ambiguous with the global operator overload.

Upvotes: 0

Related Questions