class-id MyType. operator-id + procedure division using by value o as type MyType, I as binary-long returning ret as type MyType. ... end operator. end class.
See also the Operator Overloading sample, available from Start > All Programs > Micro Focus Visual COBOL > Samples , under COBOL for JVM (Windows) or $COBDIR/demo (UNIX).
Conversion operators can be overloaded, so that the appropriate conversion operator is used according to the parameter types in the calling code. The operator with the matching signature (procedure division using clause) is executed. For example, where a data item of type Timer requires converting to binary-long, the operator used is the operator with an input parameter of type Timer and output parameter of binary-long.
To define and use conversion operators:
You can overload operators to provide alternative behavior, or behavior for different operand types. For example, where a Timer type is expressed as hours and minutes, you could define one + (plus) operator to add two Timers and another + (plus) operator to add a number of minutes to a Timer type.
To declare overloaded operators:
Operators that can be overloaded | Overload operator-id signature | Notes |
---|---|---|
Comparison operators, such as:
t1 = t2, t1 equals t2 |
value t1 t2 returning condition-value |
Comparison operators must be specified in pairs where the pairs are - equality (=) and inequality (<>) operators, greater than (>) and less than (<) operators, and greater than or equal to (>=) and less than or equal to (<=) operators.
The returning item must be of type condition-value. |
Other binary operators, such as:
t1 + t2 |
value t1 t2 returning t3 |
Binary operators have two arguments. If the two arguments are of different type, you need to specify a pair of operators to enable the two operands to be passed in either order. |
Unary operators, such as:
-t1 |
value t1 returning t3 |
Unary operators have only one argument. |
While the arithmetic operators for addition, subtraction, multiplication and division can all be overloaded, their verb equivalents cannot. For example, ADD in the following statement cannot be overloaded:
add a to b giving c