Operators overloading

The NetTradex language supports the operator overloading feature. Thus, the programmer can choose the way of functioning for any operator applied to instances of user classes. To implement the operator overloading, describe the method that has one of the following names (listed below), this method will be automatically invoked when the corresponding operator is applied.

Operations and their equivalent methods

Equivalent methods for unary prefix operators

–- opPreDec

Equivalent methods for unary postfix operators


Equivalent methods for comparison operators


1For the == and != operations, use the single opEquals method, which should return a variable of the bool type. The != operation is processed similarly, but the returned result will be the opposite.

2For the operations <,<=,>,>=, use a single opCmp method, which should return a variable of the int type. If any object passed as a method argument is larger than the instance of an object, where this method is called, the function should return a negative value when they are equal - 0 is returned.

Equivalent methods for assignment operators


Equivalent methods for binary operators


Let us overload the postfix ++ operator and the binary + operator

 class A { int a; int b; // Constructors A() { } A(int a, int b) { this.a = a; this.b = b; } // Operation ++ [email protected] opPostInc() { a++; b++; return this; } // Operation+ [email protected] opAdd(const A &in other) { A obj; obj.a = this.a + other.a; obj.b = this.b + other.b; return obj; } void Print() { System.Print("a="+a+" b="+b); } } int Run() { A x(5,10); x++; x.Print(); A y(7,11); A w(3,4); A s; s = y + w; s.Print(); return 0; } 

Indexing operator


To access the user class object elements, the function get_opIndex should be called with a single parameter - the element number. To change the method value, the method set_opIndex must be implemented with two parameters: the number of the element and the value of the parameter.

Example of using the [] operator for the user class.

 class MyArray { // Array where the values are kept array <float> x; // Getting the element value by index float get_opIndex(uint idx) { // If there is no item with this number or a number is negative if((idx > x.length-1) || (idx < 0)) { return 0; } return x[idx]; } // Setting the element value void set_opIndex(uint idx, float value) { // When the index is negative, quit immediately if(idx<0)return; // When there is no element with this index if(idx>=x.length) { for(uint i=x.length; i<idx; i++) { x.insertLast(0); } x.insertLast(value); } // When the element exists else { x[idx]=value; } } // Array content displaying void Print() { string output; for(uint i=0;i<x.length;i++) { output+=" ["+i+"]="+x[i]; } System.Print(output); } } int Run() { MyArray a; a[2]=22; a.Print(); a[4]=44; a.Print(); a[3]=33; a.Print(); return 0; } 


 [0]=0 [1]=0 [2]=22 [0]=0 [1]=0 [2]=22 [3]=0 [4]=44 [0]=0 [1]=0 [2]=22 [3]=33 [4]=44