Two ways of operator overloading
For many operators, you can choose to use member functions or non-member functions to implement operator overloading. In general, a non-member function should be a friend function so that the private data of the class can be accessed directly. For example, the addition operator of the time class is prototyped in the time class declaration:
Time operator+ (const time &t) Const;//member version
The way this member function is declared.
The declaration of this function can also make the way of the UF meta-function:
Friend Time operator+ (const time &T1, const time &T2)//nonmember version
The addition operation requires two operands, and for the member function version, an operand is implicitly passed through the this pointer, and the other operand is passed explicitly as a function parameter, and for the version of the friend function, two operands are passed as parameters.
Both prototypes match the expression T2 + T3, where both T2 and T3 are time type objects. In other words, the compiler will use the following statement:
T1 = T2 + T3; Convert to any of the following: T1 = t2.operator+ (T3);//member functionT1 = operator+ (T2, T3);//nonmember function
Remember that when you select an operator, you must select one of these formats, and you cannot select both. Because both formats match the same expression, defining both of these formats is considered a ambiguity error, resulting in a compilation error.
So which is the best format? For some operators, the member function is the only valid choice, such as the self-increment operator++ operation, the operator= operation. In other cases, the two formats are not much different.
return type for operator overloading
C + + overloaded operators