Debian Codegraph @

examples/oper/overload_overview.ck

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