开发者

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_strD开发者_如何学Goescription == 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:)


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.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜