2015年6月14日日曜日

Operator overloading in C++

overloaded operators can generally be implemented either as a
a) member function of their left operand's type
b) non-member functions

class Sample
{
 public:
    Sample operator + (const Sample& op2); //works with s1 + s2
    Sample operator + (double op2); //works with s1 + 10.0

   //Make it `friend` only when it needs to access private members. 
   //Otherwise simply make it **non-friend non-member** function.
    friend Sample operator + (double op1, const Sample& op2); //works with 10.0 + s2
}
Ordinarily, we define the arithmetic and relational operators, i.e. '+', '-', as nonmember functions in order to allow conversion for either left- or right-hand operand.

Choosing Member or Nonmember Implementation

Must be member:
Assignment(=), subscript([]), call(()), and member access arrow(->)

Should be member:
compound-assignment(+=), operators that change the state of their object or thar are closely tied to their given type, i.e. increment(++), decrement(--), dereference

Must be nonmember:
I/O operators(<<, >>)

Should be nonmember:
Symmetric operator, (+, -, *, /, ==, !=, >=, <=, bitwise operators(>>, <<))


Reference
1. http://stackoverflow.com/questions/4622330/operator-overloading-member-function-vs-non-member-function
2. http://stackoverflow.com/questions/4421706/operator-overloading