| 1 |
//----------------------------------------------------------- |
| 2 |
// the general format for overload an operator is as follows: |
| 3 |
//----------------------------------------------------------- |
| 4 |
// let's say we define a custom class... |
| 5 |
public class Foo { int num; } |
| 6 |
|
| 7 |
// persistent operator overloading (trascends contexts) |
| 8 |
// NOTE the use of 'public' instead of 'fun' -- it's fun for all! |
| 9 |
public Foo @operator =^( Foo lhs, Foo rhs ) |
| 10 |
{ /* do stuff for Foo =^ Foo */ return rhs; } |
| 11 |
|
| 12 |
// LOCAL binary operator overload for '=>' (local to this context) |
| 13 |
fun Foo @operator =>( Foo lhs, Foo rhs ) |
| 14 |
{ /* do stuff for Foo => Foo */ return rhs; } |
| 15 |
|
| 16 |
// define binary operator overload for '+' |
| 17 |
fun Foo @operator +( Foo lhs, Foo rhs ) |
| 18 |
{ Foo retval; lhs.num + rhs.num => retval.num; return retval; } |
| 19 |
|
| 20 |
// define binary operator overload for '*' |
| 21 |
fun Foo @operator *( Foo lhs, Foo rhs ) |
| 22 |
{ Foo retval; lhs.num * rhs.num => retval.num; return retval; } |
| 23 |
|
| 24 |
// define unary operator overload for '~' |
| 25 |
// NOTE: '!' is no longer overloadable as of v1.5.5.8, to support builtin |
| 26 |
// conditional checks for object reference |
| 27 |
fun int @operator ~( Foo foo ) |
| 28 |
{ return ~foo.num; } |
| 29 |
|
| 30 |
// NOTE % can be overloaded, but due to polar e.g., `%(1,pi)` |
| 31 |
// need to use the formal parenthesis notation to disambiguate |
| 32 |
fun int @operator(%)( Foo foo, int mod ) |
| 33 |
{ mod %=> foo.num; return foo.num; } |
| 34 |
|
| 35 |
// define postfix operator overload for '++' |
| 36 |
fun Foo @operator ( Foo foo ) ++ |
| 37 |
{ foo.num++; return foo; } |
| 38 |
|
| 39 |
//----------------------------------------------------------- |
| 40 |
// using the new overloaded operators |
| 41 |
//----------------------------------------------------------- |
| 42 |
// create 2 Foos |
| 43 |
Foo a, b; 1 => a.num; 2 => b.num; |
| 44 |
// operator in action (follows default ck operator precedence) |
| 45 |
a + b * b + a @=> Foo c; |
| 46 |
// post ++ on c |
| 47 |
c++; |
| 48 |
// should print 3 |
| 49 |
<<< c % 4 >>>; |