Expert Delphi
上QQ阅读APP看书,第一时间看更新

Operator overloading

Your code can be more readable with operator overloading. You cannot overload the meaning of arbitrary operators in Object Pascal, only the built-in operators. You can also implement implicit conversion operators that make it possible to assign different types to a given type and define what would happen during the assignment. You can also define comparison operators to define the results of the built-in operators, =,<, and >.

Operator overloading leads to more compact, more readable code. For example, Delphi comes with a System.Math.Vectors unit with different useful types such as TVector3D with useful overloaded operations, as shown in the following code snippet:

uses 
  System.Math.Vectors; 
 
procedure DoSomeVectorMath; 
var 
  A, B, C: TVector3D; 
begin 
  A := TVector3D.Create(1,2,4); 
  B := TVector3D.Create(2,3,1); 
  C := A + B; 
  // ... 

Another good example is the TAlphaColorF record type defined in System.UITypes, which defines different operations on colors using real numbers.

Operator overloading cannot be used with class types, only with records.