xHarbour Reference Documentation > Statement Reference xHarbour Developers Network  

METHOD...OPERATOR

Declares a method to be executed with an operator.

Syntax

METHOD <MethodName> OPERATOR <xOperator>

Arguments

<MethodName>
This is the symbolic name of the method to declare. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters.
OPERATOR <xOperator>
This is the operator which invokes the method.

Description

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>.

Info

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

Example

// 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

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe