| xHarbour Reference Documentation > Statement Reference |
![]() |
![]() |
![]() |
Declares a method to be executed with an operator.
METHOD <MethodName> OPERATOR <xOperator>
The OPERATOR option of the METHOD statement defines an operator that can be used with an object. When the object is an operand of <xOperator>, the method <MethodName> is invoked. Unary operators invoke the method without an argument while binary operators pass the second operand as argument to the method.
Note: only regular operators can be used for <xOperator>. Special operators are not supported. When <xOperator> is a binary operator, the object must be the left operand for invoking the method <MethodName>.
| See also: | CLASS, EXTEND CLASS...WITH METHOD, METHOD (implementation), OPERATOR |
| Category: | Class declaration , Declaration , xHarbour extensions |
| Header: | hbclass.ch |
| Source: | vm\classes.c |
| LIB: | xhb.lib |
| DLL: | xhbdll.dll |
// The example demonstrates how basic numeric operations can
// be implemented with objects. The example support two unary
// and two binary operators.
#include "Hbclass.ch"
PROCEDURE Main
LOCAL oNumA := Number():new( 10 )
LOCAL oNumB := NUmber():new( 2 )
? oNumA + 100 // result: 110
? oNumA + oNumB ++ // result: 13
? oNumA - oNumB // result: 7
? -- oNumA // result: 9
RETURN
CLASS Number
PROTECTED:
DATA nNumber INIT 0
EXPORTED:
METHOD init(n) INLINE (IIf(Valtype(n)=="N",::nNumber:=n,) , self)
METHOD add OPERATOR +
METHOD subtract OPERATOR -
METHOD increment OPERATOR ++
METHOD decrement OPERATOR --
ACCESS value INLINE ::nNumber
ASSIGN value(n) INLINE ::nNumber := n
ENDCLASS
METHOD add(x) CLASS Number
IF HB_IsObject(x)
RETURN ::nNumber + x:value
ENDIF
RETURN ::nNumber + x
METHOD subtract(x) CLASS Number
IF HB_IsObject(x)
RETURN ::nNumber - x:value
ENDIF
RETURN ::nNumber - x
METHOD increment CLASS Number
RETURN ++ ::nNumber
METHOD decrement CLASS Number
RETURN -- ::nNumber
http://www.xHarbour.com