"More than one operator + matches these operands" error

12,710
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).

Share:
12,710

Related videos on Youtube

a cplusplus student
Author by

a cplusplus student

learning C++ (and python). Familiar with Matlab and R

Updated on June 04, 2022

Comments

  • a cplusplus student
    a cplusplus student about 2 years

    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?

    • Cameron
      Cameron about 12 years
      You've only shown one operator+ here. Do you have another one?
    • a cplusplus student
      a cplusplus student about 12 years
      no, that's the only operator+ I've written.
    • David Rodríguez - dribeas
      David Rodríguez - dribeas about 12 years
      The Otero operator is defined in the language
  • a cplusplus student
    a cplusplus student about 12 years
    So if I add explicit to both of the constructors, what conversion is it doing when it's able to do myMoney+int?
  • Benjamin Lindley
    Benjamin Lindley about 12 years
    @acplusplusstudent: In that case, it would be doing operator+(double,double) since the int could not be converted to Money without a cast.