The decision between Member and Non-member
The binary Operators =
(Assignment), []
(array subscription), ->
(member access), as well as the N-ary ()
(fu Nction call) operator, must always be implemented as member functions, because the syntax of the language require s them to.
Other operators can is implemented either as members or as non-members. Some of them, however, usually has to being implemented as non-member functions, because their left operand cannot be modifi Ed by you. The most prominent of these is the input and output operators <<
>>
and, whose left operands is stream classes from The standard library which your cannot change.
For any operators where you have to choose to either implement them as a member function or a non-member function, use The following rules of thumb to decide:
- If It is a unary operator, implement it as a member function.
- If A binary operator treats both operands equally (it leaves them unchanged), implement this operator as a no N-member function.
- If A binary operator does not treat both of its operands equally (usually it would change its left op Erand), it might is useful to make it a member function of the It left operand ' s type, if it have to access the Ope Rand ' s private parts.
Of course, as with the all rules of thumb, there is exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
And you want to overload the increment and decrement operators for it, you cannot does this as a member functions, since in C + +, enum types cannot has member functions. So you had to overload it as a free function. And for operator<()
a class template nested within a class template was much easier to write and read when do as a member Funct Ion inline in the class definition. But these is indeed rare exceptions.
(However, if you make a exception, do not forget the issue of const
-ness for the operand, for member Functi ONS, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a me Mber function needs to has a at the const
end to make *this
a const
reference.)
----------------------------------------------------
Original: http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729
C + + operator overloading-How to determine as a member function or a non-member function