0

Possible Duplicate:
Operator Overloading in C++ as int + obj

I have a class A with an overloaded operator+. My problem is that I wish to be able to use summation in the two following ways.

A a;

a + 5;

and

5 + a;

How do I overload + to be able to do this? I am aware that we can overload ++ to perform both post and pre increment (++x and x++), so how can I simulate the above ability as well?

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253
  • You should look into an operator overloading article or reference for the latter. You can find just about everything [here](http://stackoverflow.com/questions/4421706/operator-overloading). – chris Nov 02 '12 at 14:31

1 Answers1

4

You define the operator as a non-member:

class A
{
   int operator + (int x) const
   { 
       return 42;
   }
};

inline int operator + (int x, const A& a)
{
   return a+x;  //calls a.operator +(x)
}

The inline is there to prevent defining the symbol multiple times in case you define the operator in a header.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625