Binary operator
The following table shows a list of the operators that can be overloaded.
Binary operators that can be redefined
Operator |
Name |
, |
Comma |
!= |
Not equal |
% |
Take the mold |
%= |
Modulo/Assignment |
& |
Bitwise "and" |
&& |
Logic "and" |
&= |
Bitwise AND/Assignment |
* |
Multiplication |
*= |
Multiplication/Assignment |
+ |
Add to |
+= |
Addition/Assignment |
– |
Subtraction |
–= |
Subtraction/Assignment |
< |
Less than |
<< |
Move left |
<<= |
Move Left/Assign value |
<= |
Less than or equal to |
= |
assigning values |
== |
Equal |
> |
Greater than |
>= |
Greater than or equal to |
>> |
Move right |
>>= |
Move Right/Assign value |
^ |
XOR or |
^= |
XOR/Assign Value |
| |
Bitwise AND OR |
|= |
bitwise AND OR/assignment |
|| |
Logical "or" |
To declare a two-dollar operator function as a non-static member, you must declare it in the following form:
Ret-type Operatorop (ARG)
Where Ret-type is the return type, OP is one of the operators listed in the previous table, and Arg is a parameter of any type.
To declare a two-dollar operator function as a global function, you must declare it in the following form:
Ret-type Operatorop (arg1, arg2)
Where the Ret-type and OP are member operator functions, and arg1 and arg2 are parameters. At least one parameter must be a class type.
Attention
There are no restrictions on the return type of the two-dollar operator, but most user-defined two-dollar operators return a class type or a reference to a class type.
Assignment operator
strictly speaking, the assignment operator (=) is a two-dollar operator. The declaration is the same as any other two-dollar operator, with the following exceptions:
It must be a non-static member function. No operator= can be declared as a non-member function.
It is not inherited by derived classes.
The default operator= function can be generated by the compiler of the class type, if the function does not exist. (For more information about the default operator= function, see member assignments and initialization.) )
The following example illustrates how to declare an assignment operator:
Assignment.cpp
class Point
{public
: Point
&operator= (Point &);//Right side is the argument .
int _x, _y;
};
Define assignment operator.
Point &point::operator= (Point &ptrhs)
{
_x = ptrhs._x;
_y = ptrhs._y;
return *this; Assignment operator returns left side.
}
int main ()
{
}
Note that the supplied parameter is to the right of the expression. This operator returns the object to retain the assignment operator's behavior, and the assignment operator returns the value on the left after the assignment completes. This allows you to write a statement similar to the following: