"More than one operator + matches these operands" error

a cplusplus student picture a cplusplus student · Apr 27, 2012 · Viewed 12.2k times · Source

I'm creating a Money class for a school assignment. I've defined a conversion from Money to double, I have a constructor for Money that takes an int, another constructor takes a double, and I've overloaded the "+" operator to add together two objects of type Money. The error message comes up when I try to do something like myMoney + 10 where my myMoney is an object of type Money, and 10 is obviously an integer. Here's the rest of the relevant code:

class Money {
private:
    int dollars;
    int cents;
public:
    Money(double r);
    Money(int d) : dollars(d), cents(0) {}
    operator double();
}

Money operator+(Money a, Money b) {
    double r = double(a) + double(b);
    return Money(r);
}

Money::operator double() {
    return dollars+double(cents)/100;
}

Money::Money(double r) {
    ...
}

The program actually works if I try Money(double(myMoney)+10) and also if I make both constructors explicit, but I'm not sure I understand what's happening with the automatic conversions otherwise. Can anyone explain this behavior?

Answer

Benjamin Lindley picture Benjamin Lindley · Apr 27, 2012
MyMoney + 10

Since there's no operator+(Money, int), some conversions have to be made here. The compiler could convert the Money to a double, then convert the 10 to a 'double' and choose the built-in operator+(double,double), or it could convert the int to Money and choose your operator+(Money,Money).