Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Byte.d

Part of OperatorOverloadingCategory

Description

A very simple class that shows the use of operator overloadings.

Example

/*
 * ***************************************************************************
 * Byte.d - Show operator overloading and some properties
 * Bruno A. Costa (brunoacf AT elitemail DOT org)
 * ******************************************************************************
 */

class Byte
{

private:
    byte _value;

public:
    this ( ) {
        _value = 0;
    }

    this (byte bt) {
    _value = bt;
    }

    this (Byte bt) {
        _value = bt.value;
    }

    /* Set Property */
    byte value (byte bt) {
        return _value = bt;
    }

    /* Set Property */
    byte value (Byte bt) {
        return _value = bt.value;
    }

    /* Get Property */
    byte value ( ) {
        return _value;
    }

    /* Overload operator == */
    int opEquals (byte bt) {
        return _value == bt;
    }

    /* Overload operator == */
    int opEquals (Byte bt) {
        return _value == bt.value;
    }

    /* Overload operator + (Byte + Byte) */
    Byte opAdd (Byte bt) {
        Byte newbt = new Byte();
        newbt.value = _value + bt.value;
        return newbt;
    }

    /* Overload operator + (Byte + byte) */
    Byte opAdd (byte bt) {
        Byte newbt = new Byte();
        newbt.value = _value + bt;
        return newbt;
    }

    /* Overload operators > >= < <= */
    int opCmp (Byte bt) {
         return (_value - bt.value);
    }
}

int main ( )
{
    Byte b = new Byte(2);
    Byte b2 = new Byte(2);
    byte b4 = 10;


    if (b == b2) printf ("b == b1\n");      /* call opEquals */

    Byte b3 = new Byte (b + b2);            /* call opAdd (Byte) */

    if (b3 < b2) printf ("b3 > b2\n");      /* call opCmp */

    b = b2 + b4;                            /* call opAdd (byte) */

    printf ("b2 + b4 = %i\n", b.value);

    /* Show values returned from opCmp( ) */
    /* 1 == true; 0 == false */
    printf ("b2 > b3: %i\n", (b2 > b3) );
    printf ("b2 < b3: %i\n", (b2 < b3) );
    printf ("b2 >= b3: %i\n", (b2 >= b3) );
    printf ("b2 <= b3: %i\n", (b2 <= b3) );

    return 0;
}

Source

Link http://www.dsource.org/tutorials/index.php?show_example=96
Posted by Anonymous
Date/Time Fri Jun 11, 2004 9:47 am