typeSizealiaslong;typeCounterstruct{Sizevalue}pCounter.ctor(longinitialValue=0l){this.value=initialValue;}f<Size>Counter.getValue(){returnthis.value;}/** * Here we define the plus operator for lhs of type Counter and rhs of type Counter * * @param c1 Counter 1 * @param c2 Counter 2 * @return New counter with the sum of c1 and c2 */f<Counter>operator+(constCounter&c1,constCounter&c2){returnCounter(c1.value+c2.value);}f<int>main(){Countercounter1=Counter(2l);Countercounter2=Counter(3l);printf("Counter1 value: %d\n",counter1.getValue());printf("Counter2 value: %d\n",counter2.getValue());Countercounter3=counter1+counter2;// Here we call the overloaded operatorprintf("Counter3 value: %d\n",counter3.getValue());}
The relational operators <, >, <= and >= can be overloaded as well. Each of them is looked up on its own, so
define all of the ones you use. This makes struct types usable in containers like PriorityQueue, that order their items
with <:
A generic less operator is written as operator<<T>(...): the < operator, followed by the template type list. The shift
left operator is still recognized, if the parameter list or a template type list follows (operator<<(...) or
operator<<<T>(...)).