Why must operator <> operator Overloading be a friend function ?, Operator overload
If the operator is an overloaded binary operator (a member function of the class), you only need to set a parameter as the calculation amount on the right side, and the calculation amount on the left side is the object itself ......
And> or <the left side of the calculation is cin or cout rather than the object itself, so it does not meet the following requirements ........ It can only be declared as a friend function...
If it must be declared as a member function, it can only be in the following form:
Ostream & operator <(ostream & output)
{
Return output;
}
Therefore, this <operator is used in the form of data <cout;
The habit of not matching people.
Operator overload functions can be used as member functions, friend functions, and common functions.
Common functions: Generally, Private Members are indirectly accessed through public interfaces of the class.
Member function: You can use the this pointer to access the members of this class. You can write less than one parameter. However, the first parameter on the left of the expression must be a class object. You can call the member function through this class object.
Friend functions: the left side is generally not an object. <> Generally, operators must be declared as friends-element overload functions.
Generally:
The binary operator is overloaded as a friend function, so that the exchange law can be used, which is more convenient.
The single-object operator is typically overloaded as a member function, because operations are directly performed on the class object itself.
In short: If the operator overload is a member function, the first parameter must be the object of this class, because the object of the first parameter is used by default to call this member function.