This system can be used to declare a new type, and de ne an assignment for that type. For instance, to be able to assign a newly de ned type 'Complex'
Var
C,Z : Complex; // New type complex begin Z:=C; // assignments between complex types. end; |
The following assignment operator would have to be de ned:
Operator := (C : Complex) z : complex;
|
To be able to assign a real type to a complex type as follows:
var
R : real; C : complex; begin C:=R; end; |
the following assignment operator must be de ned:
Operator := (r : real) z : complex;
|
As can be seen from this statement, it de nes the action of the operator := with at the right a real expression, and at the left a complex expression.
an example implementation of this could be as follows:
operator := (r : real) z : complex;
begin z.re:=r; z.im:=0.0; end; |
As can be seen in the example, the result identi er (z in this case) is used to store the result of the assignment. When compiling in Delphi mode or objfpc mode, the use of the special identi er Result is also allowed, and can be substituted for the z, so the above would be equivalent to
operator := (r : real) z : complex;
begin Result.re:=r; Result.im:=0.0; end; |
The assignment operator is also used to convert types from one type to another. The compiler will consider all overloaded assignment operators till it nds one that matches the types of the left hand and right hand expressions. If no such operator is found, a 'type mismatch' error is given.
Remark: The assignment operator is not commutative; the compiler will never reverse the role of the two arguments. in other words, given the above de nition of the assignment operator, the following is not possible:
var
R : real; C : complex; begin R:=C; end; |
if the reverse assignment should be possible (this is not so for reals and complex numbers) then the assigment operator must be de ned for that as well.
Remark: The assignment operator is also used in implicit type conversions. This can have unwanted e ects. Consider the following de nitions:
operator := (r : real) z : complex;
function exp(c : complex) : complex; |
then the following assignment will give a type mismatch:
Var
r1,r2 : real; begin r1:=exp(r2); end; |
because the compiler will encounter the de nition of the exp function with the complex argument. It implicitly converts r2 to a complex, so it can use the above exp function. The result of this function is a complex, which cannot be assigned to r1, so the compiler will give a 'type mismatch' error. The compiler will not look further for another exp which has the correct arguments.
It is possible to avoid this particular problem by specifying
r1:=system.exp(r2);
|
An experimental solution for this problem exists in the compiler, but is not enabled by default. Maybe someday it will be.