-3

I want to implement the operator "+" with the help of delegation. But when I want to use the "+ =" operator, it cannot find it.

Money Money::operator +=(const Money &m)noexcept
{
    rouble += m.rouble;
    penny += m.penny;
    return *this;
}

Money operator + (const Money &first, const Money &second) noexcept
{
    return operator+=(second);
           ^^^^^^^^^
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684
ANurbaev
  • 17
  • 3
  • Please provide a [complete, verifiable example](https://stackoverflow.com/help/mcve) we can check. – einpoklum Apr 21 '19 at 11:13
  • The return statement needs to return to `first`; it doesn't. For example `return first.operator+=(second)` – Peter Apr 21 '19 at 11:34
  • Note that this problem has nothing to do with operator overloading. If you change `operator +=` to `my_func` everywhere you'll have the same problem. – Pete Becker Apr 21 '19 at 12:15

1 Answers1

3

Your second function (operator+) is free-standing, it is not a member. Your first function (Money::operator+=) is a member function; you can't just use the += member function as though it was free-standing.

So, in your second function, you probably want to do something like:

Money operator+ (const Money &first, const Money &second) noexcept
{
    Money sum{first}; 
    sum += second; 
    return sum; 
}

Having said that - you should also follow @πάνταῥεῖ's advice and read:

What are the basic rules and idioms for operator overloading?

einpoklum
  • 118,144
  • 57
  • 340
  • 684