| 1 |
// global operator overloading using the 'public' keyword |
| 2 |
// overloading an operator in one context, and using it in another |
| 3 |
// |
| 4 |
// requires chuck-1.5.5.8 or higher |
| 5 |
|
| 6 |
// a custom class |
| 7 |
public class Foo |
| 8 |
{ 5 => int n; } |
| 9 |
|
| 10 |
// binary operator overloading |
| 11 |
// NOTE the use of 'public' keyword |
| 12 |
public int @operator +(Foo lhs, Foo rhs) |
| 13 |
{ |
| 14 |
return lhs.n + rhs.n; |
| 15 |
} |
| 16 |
|
| 17 |
// unary prefix overloading |
| 18 |
// NOTE: '!' is no longer overloadable as of v1.5.5.8, |
| 19 |
// in order to support conditional checks, e.g., if(!obj) |
| 20 |
public int @operator ~(Foo foo) |
| 21 |
{ |
| 22 |
return !foo.n; |
| 23 |
} |
| 24 |
|
| 25 |
// unary postfix overloading |
| 26 |
public int @operator (Foo foo) ++ |
| 27 |
{ |
| 28 |
return foo.n++; |
| 29 |
} |
| 30 |
|
| 31 |
// use the overloading in a different code context |
| 32 |
// (could be another file; here we use Machine.eval()) |
| 33 |
Machine.eval( "Foo a, b; <<<a++, ~b, a+b>>>;" ); |