The operations object of a predefined operator in the C + + language can only be the base data type. However, in practical applications, similar functionality is required for many user-defined data types (such as classes), which requires a multiplicity of meanings for an existing operator, so that the same operator has data that acts on different classes, causing different types of behavior , which is the operator overload. Therefore, the purpose of operator overloading is to set an operator in the C + + language so that there is no conflict between them, and the C + + language will identify which function should be used to perform the operation based on the position of the operator. As you can see, the advantage of operator overloading is that it allows you to change the operation of the operators used inside the system to accommodate similar operations for the user's newly defined types.
The essence of operator overloading is function overloading. In fact, each operator in the C + + language corresponds to an operator function, in which the operator in the specified operation expression is converted to a call to the operator function, and the operational object in the expression is converted to the actual parameter of the operator function, which is done at compile time. For example:
int a=1,b=2;
A+b;
The expression "A+b" is interpreted as a function call form before compiling: operator+ (a,b).
Where operator is a keyword, which together with the following "+" makes up the function name of the operator function.
Operator overloading is a special type of function overload. In a class, you can overload an operator function with the following two methods.
1. Overload as a member function of a class
Overloading an operator function as a member function of a class means defining an operator function with the same name in the class, with the statement in the form:
TYPE x::operator@ (formal parameter list)
{
function body
Redefining the functionality of the operator @ in the specified class X
}
Where operator is the keyword, @ is the operator that needs to be overloaded, X is the class name that requires overloading the operator, and type is the return value type of the operator function. The keyword operator, together with the following operator @, makes up the function name of the operator function.