Next: Translating, Previous: Class initialization, Up: Methods [Index]
Methods can also overload C unary operators like ‘*’, ‘&’, ‘!’, ‘~’, and ‘sizeof’. For most unary operators, if the class defines a method to overload the operator, then Ctalk uses the method; otherwise, it treats the operator as a normal C operator.
Methods that overload unary operators contain the
__prefix__ attribute in their declaration. This
simplifies method writing considerably, because that allows
a class to define two different method ‘*’ methods, for
example, one a unary dereference operator, the other a
multiplication operator.
In the method’s declaration, use the __prefix__
attribute in place of paramter declarations, as in this example.
String instanceMethod * deref_prefix (__prefix__) {
... Method statements here ...
}
When Ctalk encounters a ‘sizeof’ operator, it checks whether the
argument is a Ctalk object, or a C variable or type cast expression.
If the argument is a C variable or type cast expression, then Ctalk
uses the C sizeof operator. Otherwise, it uses the
sizeof method (Object class). This method’s
implementation is simple: it treats a Ctalk object as an OBJECT
*, and returns the size in bytes of a pointer on the system. On
32-bit systems, the sizeof method always returns 4. However,
you can overload the ‘sizeof’ operator in your own classes if
necessary.
You need to take care when using unary operators in complex
statements, due to the precedence of Ctalk’s method messages. In the
following highly experimental example, you would need to use
parentheses to specify the order of evaluation, because the expression
needs the result of (*s) asString to be a String also.
String new s; String new sFirstChar; Character new c; Integer new i; s = "Hello, "; sFirstChar = (*s) asString;
Ctalk also provides postfix equivalents for many of these operators,
like deref (class Symbol) and invert
(Character, Integer, and LongInteger classes).
Ctalk can overload these operators even if the class defines a method that uses the operator with an argument. For example, the pointer (‘*’) and unary minus (‘-’) operators can have different methods than the methods that perform multiplication and subtraction.
The subject of method overloading is discussed further in its own section. See Overloading.
Next: Translating, Previous: Class initialization, Up: Methods [Index]