To define the action of an operator is much like defining a function:
_________________________________________________________________________________________________________
Operator definitions
____________________________________________
The parameter list for a comparison operator or an arithmetic operator must always contain two parameters, with the exception of the unary minus or plus, where only one parameter is needed. The result type of the comparison operator(s) must be Boolean.
User-defined simple types can be used for operators, as well as records and arrays. There are some limitations on operator overloading:
This way of declaring operators is only supported in ObjFPC and FPC modes.
It is not possible to define operators on classes.
The + and - operators cannot be defined on enumerated types.
When the ArrayOperators modeswitch is in effect:
{$modeSwitch ArrayOperators}
then the + operator cannot be overloaded on dynamic arrays, because it is handled internally by the compiler.
Remark When compiling in Objfpc mode, the result identifier may be dropped. The result can then be accessed through the standard Result symbol.
If the result identifier is dropped and the compiler is not in one of these modes, a syntax error will occur.
The statement block contains the necessary statements to determine the result of the operation. It can contain arbitrary large pieces of code; it is executed whenever the operation is encountered in some expression. The result of the statement block must always be defined; error conditions are not checked by the compiler, and the code must take care of all possible cases, throwing a run-time error if some error condition is encountered.
In the following, the three types of operator definitions will be examined. As an example, throughout this chapter the following type will be used to define overloaded operators on:
type complex = record re : real; im : real; end;
This type will be used in all examples.
The sources of the Run-Time Library contain two units that heavily use operator overloading:
This unit contains a complete calculus for complex numbers.
This unit contains a complete calculus for matrices.