简体   繁体   中英

overloading operator+ twice (inside and outside class)

Why am I allowed to do this, why there is no ambiguity complain, and why is the class' method chosen with prior to the other one?

class EX
{
public:
    //...

    void operator+(const EX& ref)
    {
        cout << "A";
    }
};

void operator+(const EX& ref1, const EX& ref2)
{
    cout << "B" << endl;
}

int main()
{
    EX obj1{20};
    EX obj2{30};


    cout << "obj1 + obj2 = " <<  obj1 + obj2 << endl;

    return 0;
}

I was expecting the global function operator+ to be called an "B" printed on the screen, instead "A" was printed.

Your member overload accepts only non-const instances of EX for the first operand while the free overload accepts both const and non-const instances. By overload resolution rules, the non-const wins out because it exactly matches the type being passed in.

You'll get an ambiguity error if you make the member overload const, indicating that *this is const:

void operator+(const EX& ref) const
{
    cout << "A";
}

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