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 .NET .
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 |
---|---|---|
Conditional operators, such as:
t1 = t2, t1 equals t2 |
value t1 t2 returning condition-value |
Conditional operators must be specified in pairs. If you declare an equality operator (=), you must also declare an inequality operator (<>).
The returning item must be of type condition-value. |
Binary operators, such as:
t1 + t2 |
value t1 t2 returning t3 |
Binary operators must have two arguments. For binary operators, you might 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 overloaded operators can have only one argument. |
Logical operators, such as:
t1 b-or |
value t1 t2 returning t3 |
|
Shift operators, such as:
t1 b-right |
value t1 t2 returning t3 |
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
To use overloaded operators, the overloaded operator must be in scope.