operator+ overloading

Hans Aberg haberg-1 at telia.com
Thu Jan 12 00:45:51 CET 2012


On 11 Jan 2012, at 15:54, Slava Feshchenko wrote:

> I am building a class (called Money)  for handling monetary values and use
> GNU MP as a back end for the calculations. I can't seem to be able to
> overload operator+.
...
> The broken code for operator+ is as follows:
> 
> Money & Money::operator+(Money &m)
> {
> Money temp;
> mpz_add(temp.monetaryUnit, this->monetaryUnit, m.monetaryUnit);
> return temp;
> }

The type should normally be
  A operator+(const A&, const A&);
for this and other arithmetic operators, as the arguments are not modified. If you put the function definition in the header and inline, it will normally be removed, and if not, the copying of the temporary will go away by return value optimization.

There is a GMP C++ wrap you might look at (see manual). And if you so like, I can send you a C++ wrap I have made.

Hans




More information about the gmp-discuss mailing list