delphi 运算符重载

譬如上面的 record 可以这样声明:

type
  TMyRec = record
    name: string;
    age: Word;
    class operator GreaterThan(a,b: TMyRec): Boolean;
  end;


还得有方法的实现(遗憾的是有些不能用 Ctrl+Shift+C 自动建立, 那就复制吧):

class operator TMyRec.GreaterThan(a,b: TMyRec): Boolean; {注意复制后再加上方法名: "TMyRec."}
begin
  Result := a.age > b.age;
end;

 

Delphi for Win32 只支持 record 类型的运算符重载,而 Delphi .NET 还支持 class 类型的运算符重载
下面是Delphi支持的可重载运算符

运算符       类型       声明语法                                          应用符号
Implicit     转换       Implicit(a: type): resultType;                    隐式转换

Explicit     转换       Explicit(a: type): resultType;                    显式转换

负           一元运算   Negative(a: type): resultType;                    -

正           一元运算   Positive(a: type): resultType;                    +

递增         一元运算   Inc(a: type): resultType;                         Inc

递减         一元运算   Dec(a: type): resultType;                         Dec

逻辑非       一元运算   LogicalNot(a: type): resultType;                  not

按位非       一元运算   BitwiseNot(a: type): resultType;                  not

截取         一元运算   Trunc(a: type): resultType;                       Trunc

舍入         一元运算   Round(a: type): resultType;                       Round

等于         比较       Equal(a: type; b: type) : Boolean;                =

不等于       比较       NotEqual(a: type; b: type): Boolean;              <>

大于         比较       GreaterThan(a: type; b: type) Boolean;            >

大于等于     比较       GreaterThanOrEqual(a: type; b: type): resultType;>=

小于         比较       LessThan(a: type; b: type): resultType;           <

小于等于     比较       LessThanOrEqual(a: type; b: type): resultType;    <=

加           二元运算   Add(a: type; b: type): resultType;                +

减           二元运算   Subtract(a: type; b: type): resultType;           -

乘           二元运算   Multiply(a: type; b: type): resultType;           *

除           二元运算   Divide(a: type; b: type): resultType;             /

整除         二元运算   IntDivide(a: type; b: type): resultType;          div

模           二元运算   Modulus(a: type; b: type): resultType;            mod

左移         二元运算   ShiftLeft(a: type; b: type): resultType;          shl

右移         二元运算   ShiftRight(a: type; b: type): resultType;         shr

逻辑与       二元运算   LogicalAnd(a: type; b: type): resultType;         and

逻辑或       二元运算   LogicalOr(a: type; b: type): resultType;          or

逻辑异或     二元运算   LogicalXor(a: type; b: type): resultType;         xor

按位与       二元运算   BitwiseAnd(a: type; b: type): resultType;         and

按位或       二元运算   BitwiseOr(a: type; b: type): resultType;          or

按位异或     二元运算   BitwiseXor(a: type; b: type): resultType;         xor

posted @ 2019-09-02 08:39  h2z  阅读(427)  评论(0编辑  收藏  举报