As a side note:
You can use it on classes in the Delphi .NET compiler (which since then has been discontinued) as the .NET garbage collection will eventually remove the new object instances returned by the operators, and more recently on the ARC based Delphi ARM compilers (that also release memory based on reference counting).
To answer your question:
You cannot use it on classes in the native Delphi compilers that do not support ARC (currently the Intel based x86 and x64 compilers for Windows, OS X and iOS simulator do not have ARC support), as it would heavily leak memory because the operators would return new object instances that nobody would free.
With the introduction of ARC (currently the ARM based mobile platforms), you can as those compiler compile this fine.
Notes:
- be careful redefining existing Delphi types like TDateTime
- be aware you can only use the below on ARC compilers so you are writing highly platform dependent code
- if you want to be cross platform, make it a value type like the TTimeStamp
record
is
In the code below (which only works for ARC), replace class
with record
do make it cross platform. It isn't by coincidence that the .NET framework has TimeSpan and DateTime (on which you might have based your code) are struct value types, not as class reference types.
To summarise, when writing cross platform code be aware of value and reference types and favour the record
value type when using operator overloading.
type
TTimeSpan = class
Ticks: Longint;
end;
TDateTime = class
public
Ticks: Longint;
class operator Add(a: TDateTime; b: TTimeSpan): TDateTime;
class operator Subtract(a: TDateTime; b: TTimeSpan): TDateTime;
constructor Create(aTicks: Longint);
end;
class operator TDateTime.Add(a: TDateTime; b: TTimeSpan): TDateTime;
begin
Result := TDateTime.Create(a.Ticks + b.Ticks);
end;
constructor TDateTime.Create(aTicks: Integer);
begin
Ticks := aTicks;
end;
class operator TDateTime.Subtract(a: TDateTime; b: TTimeSpan): TDateTime;
begin
Result := TDateTime.Create(a.Ticks - b.Ticks);
end;