While I feel the previous answers are good enough, I believe some clarification is needed.
Operators come (usually) in two flavors
The first being the non-member functions, the second being the member function whose parameter is the "right operand" of the operation and which usually returns the current modified object.
For example, imagine there's an operator "§" for a class T. It could be written either as a non-member function:
T operator § (const T & lhs, const T & rhs)
{
T result ;
// do the lhs § rhs operation, and puts the result into "result"
return result ;
}
or as a member function:
T & T::operator § (const T & rhs)
{
// do the "this § rhs" operation, and puts the result into "this"
return *this ;
}
or even (very unusually) as another member function:
T T::operator § (const T & rhs) const
{
T result ;
// do the "this § rhs" operation, and puts the result into "result"
return result ;
}
Usually, you should prefer the non-member function, if only because you should not declare it friend. Thus, using non-member non-friend function enhance the encapsulation of your object.
Disclaimer: There are other flavors, but I'm limiting myself to arithmetic operators like +, *, / -, etc., here, as well as "credible" operator prototypes.
Analyse your use of the operator
In the case of "+":
- each operand needs to be constant because a = b + c must not change b, nor c.
you can accumulate "+", like in a = b + c + d + e, so temporaries must exist.
T operator § (const T & lhs, const T & rhs)
{
T result ;
// do the lhs § rhs operation, and puts the result into "result"
return result ;
}
In the case of "+=":
- You know the left operand A (from A += B) will be modified
- You know the left operand A (from A += B) is its own result
So you should use:
T & T::operator += (const T & rhs)
{
// do the "this § rhs" operation, and puts the result into "this"
return *this ;
}
As always, premature optimization is the root of all evil
I've seen this kind of code in production code so, it does happen:
T & operator + (const T & lhs, const T & rhs)
{
static T result ; // result is STATIC !!!!
// do the lhs + rhs operation, and puts the result into "result"
return result ;
}
The author hoped to economize one temporary. With this kind of code, writing "a = b + c + d" leads to interesting (and wrong) results.
^_^
Last but not least
I did write a list of operator overloading prototypes in the following page
http://www.augias.org/paercebal/tech_doc/doc.en/cpp.basic.operator_overloading_prototype.html
The page is still on construction, but its main use (easy to copy/paste working prototypes) can be quite useful...