I found a way to do what I wanted. I know that operator overloading := impossible, however, forcing the compiler to perform the same behavior as the operator with overloading is possible.
Overloading did not allow me to control LSA (left side argument). but he completely controlled the implicit conversion of any TType (in my case it is integer ) to TXinteger . So all I had to do was make sure that each statement would result in a TType , which would cause the compiler to implicitly convert it to TXinteger .
Forcing the compiler to use my implicit statement every time it wants to assign something to a TXinteger , then I control the assignment. So I overloaded the operator := .
an example is given that eliminates the possibility of Line (1).
program Project4; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type TXinteger = record X: integer; class operator Add(a, b: TXinteger): integer; class operator Add(a: TXinteger; b:integer): integer; class operator Add(a: integer; b:TXinteger): integer; class operator Implicit(a: Integer): TXinteger; class operator Implicit(a: TXinteger): Integer; end; // Example implementation of Add class operator TXinteger.Add(a, b: TXinteger): integer; begin result := aX + bX; end;(**) class operator TXinteger.Add(a: TXinteger; b:integer): integer; begin result := aX + b; end; class operator TXinteger.Add(a: integer; b:TXinteger): integer; begin result := a + bX; end; class operator TXinteger.Implicit(a: Integer): TXinteger; const Xmax: integer = 10; begin if a > Xmax then result.X := 0 else result.X := a; end; class operator TXinteger.Implicit(a: TXinteger): Integer; begin result := aX; end; var X: TXinteger; Hn, F, i,J, n: integer; begin try F := 7; n := 10; Hn := n * 2 ; X := 0; i := 1; J := 1; while J < Hn do begin X := X + F * (1 - i div n); // Line (1) is gone now. if i >= n then Dec(i) else Inc(i); Inc(J); end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
Note: for this case it makes no sense to do all this simply to omit one line of code. I would like to share this because it gives an idea of how to overload the := operator.
What I wanted was:
- Change the reading method of
X:Integer (value read from x variable storage). - Change the way
X:Integer .
Overloading all the operators that use the value of X, I completed the first. And, forcing the compiler, as explained above, I completed the second.
Thank you all for your help.
source share