"More than one operator + matches these operands" error
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)
.
Related videos on Youtube
a cplusplus student
learning C++ (and python). Familiar with Matlab and R
Updated on June 04, 2022Comments
-
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 about 12 yearsYou've only shown one
operator+
here. Do you have another one? -
a cplusplus student about 12 yearsno, that's the only
operator+
I've written. -
David Rodríguez - dribeas about 12 yearsThe Otero operator is defined in the language
-
-
a cplusplus student about 12 yearsSo if I add explicit to both of the constructors, what conversion is it doing when it's able to do
myMoney+int
? -
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.