简体   繁体   中英

Why this code does not generate an ambigous call error?

I have written a MyComplex class and overloaded the plus (+) operator as:

class MyComplex
{
public:
        operator int() { return realPart; }
        MyComplex(int r, int i=0)
        {
                realPart = r;
                imaginaryPart = i;
        }

    int operator +(int i) { return imaginaryPart+i; }
private:
        int realPart, imaginaryPart;
};

int main()
{
        MyComplex c(5, 4);
        cout << c+10 << "\n"; // Why is this not ambiguous?
}

I thought the expression c+10 could be interpreted either as an attempt to add two integers ( c in c+10 would be demoted to an integer using the conversion operator operator int() ) or as an overload operator call through the overload operator function int operator +(int i) . But the program compiled without any errors and produced the output as 14. How?

When we figure out what c+10 means, we do a process called overload resolution, which starts by finding all the viable candidates through name lookup.

The viable candidates in this case are:

MyComplex::operator+(MyComplex&, int); // via c.operator+(10)
::operator+(int, int);                 // via c.operator int() + 10

We then look at which conversion sequence is better. For the first overload, no conversions are necessary - c is an Exact Match for MyComplex and 10 is an Exact Match for int . For the second overload, the second argument is an exact match but the first argument has to undergo a user-defined conversion via MyComplex::operator int() .

Exact Match has higher rank than Conversion, so the first overload is preferred.


Note that if instead your MyComplex::operator+() took a long (for example), then the call would be ambiguous. Each overload would have one better and one worse conversion sequence.

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