|
|
The operator keyword is used to create overloaded operator functions. Operator functions come in two varieties: member and nonmember. The general form of a member operator function is shown here:
ret-type class-name::operator#(param-list) { // ... }
Here, ret-type is the return type of the function, class-name is the name of the class for which the operator is overloaded, and # is the operator to be overloaded. When overloading a unary operator, the param-list is empty. (The operand is passed implicitly in this.) When overloading a binary operator, the param-list specifies the operand on the right side of the operator. (The operand on the left is passed implicitly in this.)
For nonmember functions, an operator function has this general form:
ret-type operator#(param-list) { // ... }
Here, param-list contains one parameter when overloading a unary operator and two parameters when overloading a binary operator. When overloading a binary operator, the operand on the left is passed in the first parameter, and the operand on the right is passed in the right parameter.
Several restrictions apply to operator overloading. You cannot alter the precedence of the operator. You cannot change the number of operands required by an operator. You cannot change the meaning of an operator relative to C++’s built-in data types. You cannot create a new operator. The preprocessor operators # and ## cannot be overloaded. You cannot overload the following operators:
. :: .* ?
|
|