Delphi 中记录操作重载(Operator Overloading)

一、关于记录操作重载

        Delphi 允许在记录声明中重载某些函数或 "操作符"。操作符函数的名称映射到源代码中的符号表示。例如,Add 运算符映射到 + 符号。

        编译器会根据操作符函数的名称,生成对相应重载的调用,并匹配上下文(即返回类型和调用中使用的参数类型)。

        下表列出了可以重载的 Delphi 运算符: 

OperatorCategoryDeclaration SignatureSymbol Mapping

Implicit

Conversion

Implicit(a : type) : resultType;

implicit typecast

Explicit

Conversion

Explicit(a: type) : resultType;

explicit typecast

Negative

Unary

Negative(a: type) : resultType;

-

Positive

Unary

Positive(a: type): resultType;

+

Inc

Unary

Inc(a: type) : resultType;

Inc

Dec

Unary

Dec(a: type): resultType

Dec

LogicalNot

Unary

LogicalNot(a: type): resultType;

not

Trunc

Unary

Trunc(a: type): resultType;

Trunc

Round

Unary

Round(a: type): resultType;

Round

In

Set

In(a: type; b: type) : Boolean;

in

Equal

Comparison

Equal(a: type; b: type) : Boolean;

=

NotEqual

Comparison

NotEqual(a: type; b: type): Boolean;

<>

GreaterThan

Comparison

GreaterThan(a: type; b: type) Boolean;

>

GreaterThanOrEqual

Comparison

GreaterThanOrEqual(a: type; b: type): Boolean;

>=

LessThan

Comparison

LessThan(a: type; b: type): Boolean;

<

LessThanOrEqual

Comparison

LessThanOrEqual(a: type; b: type): Boolean;

<=

Assign

Binary

Assign(var Dest: type; const [ref] Src: type);

:=

Add

Binary

Add(a: type; b: type): resultType;

+

Subtract

Binary

Subtract(a: type; b: type) : resultType;

-

Multiply

Binary

Multiply(a: type; b: type) : resultType;

*

Divide

Binary

Divide(a: type; b: type) : resultType;

/

IntDivide

Binary

IntDivide(a: type; b: type): resultType;

div

Modulus

Binary

Modulus(a: type; b: type): resultType;

mod

LeftShift

Binary

LeftShift(a: type; b: type): resultType;

shl

RightShift

Binary

RightShift(a: type; b: type): resultType;

shr

LogicalAnd

Binary

LogicalAnd(a: type; b: type): resultType;

and

LogicalOr

Binary

LogicalOr(a: type; b: type): resultType;

or

LogicalXor

Binary

LogicalXor(a: type; b: type): resultType;

xor

BitwiseAnd

Binary

BitwiseAnd(a: type; b: type): resultType;

and

BitwiseOr

Binary

BitwiseOr(a: type; b: type): resultType;

or

BitwiseXor

Binary

BitwiseXor(a: type; b: type): resultType;

xor

        除表中列出的操作符外,记录中不得定义其他操作符。

        重载的操作符方法不能在源代码中通过名称引用。要访问特定记录的特定操作符方法,请参阅 下面示例)。运算符标识符包含在以 "运算符 "开头的语言记录方法列表中(例如:System.AnsiStringBase 方法)。您可以在自己的记录中实现上述任何操作符。

         只要符合以下条件,编译器就会为记录使用运算符:

  • 对于二元运算符,其中一个输入参数必须是记录类型。
  • 对于一元运算符,输入参数或返回值必须是记录类型。
  • 对于使用相同符号的逻辑运算符和位运算符,逻辑运算符仅在操作数为布尔时使用。由于此记录运算符的记录类型不是布尔型,因此只有当另一个操作数是布尔型时,才会使用逻辑运算符。

不对运算的分配或交换性质做任何假设。对于二元运算符,第一个参数总是左操作数,第二个参数总是右操作数。在没有明确括号的情况下,关联性被假定为从左到右。

操作符方法的解析是在操作中使用的类型的可访问操作符的联合体上完成的(注意这包括继承操作符)。对于涉及两个不同类型 A 和 B 的操作,如果 A 类型隐式转换为 B 类型,而 B 类型隐式转换为 A 类型,就会产生歧义。只有在绝对必要的情况下才提供隐式转换,并应避免反向性。最好让 B 类型隐式地转换为 A 类型,而让 A 类型不知道 B 类型(反之亦然)。

一般来说,操作符不应修改其操作数。相反,应通过对参数执行操作来返回一个新值。

重载操作符最常用于记录(即值类型)。
 

注意:记录助手(Record helpers)不支持操作符重载。

二、声明操作符重载

操作符重载在记录中声明,语法如下:

type
   typeName = record
       class operator conversionOp(a: type): resultType;
       class operator unaryOp(a: type): resultType;
       class operator comparisonOp(a: type; b: type): Boolean;
       class operator binaryOp(a: type; b: type): resultType;
   end;

重载操作符的实现也必须包含类操作符(class operator)语法: 

class operator typeName.conversionOp(a: type): resultType;
class operator typeName.unaryOp(a: type): resultType;
class operator typeName.comparisonOp(a: type; b: type): Boolean;
class operator typeName.binaryOp(a: type; b: type): resultType;

下面是一些重载操作符的示例: 

type
   TMyRecord = record
     class operator Add(a, b: TMyRecord): TMyRecord;      // Addition of two operands of type TMyRecord
     class operator Subtract(a, b: TMyRecord): TMyRecord; // Subtraction of type TMyRecord
     class operator Implicit(a: Integer): TMyRecord;      // Implicit conversion of an Integer to type TMyRecord
     class operator Implicit(a: TMyRecord): Integer;      // Implicit conversion of TMyRecordto Integer
     class operator Explicit(a: Double): TMyRecord;       // Explicit conversion of a Double to TMyRecord
   end;

// Example implementation of Add
class operator TMyRecord.Add(a, b: TMyRecord): TMyRecord;
begin
   // ...
end;

var
x, y: TMyRecord;
begin
   x := 12;      // Implicit conversion from an Integer
   y := x + x;   // Calls TMyRecord.Add(a, b: TMyRecord): TMyRecord
   b := b + 100; // Calls TMyRecord.Add(b, TMyRecord.Implicit(100))
end;

再举一个示例:

TPassphrase = record
  private
    FType: TPassphraseType;
    FValue: TBytes;
    FKey: TBytes;
    FInitVector: TBytes;
  public
    class operator Implicit(const Value: string): TPassphrase;
    class operator Implicit(const Value: TBytes): TPassphrase;
    constructor Create(const Key, InitVector: TBytes); overload;
    constructor Create(const Password: string; Encoding: TEncoding); overload;
  end;

{ TPassphrase }

class operator TPassphrase.Implicit(const Value: string): TPassphrase;
begin
  Result.FType := ptPassword;
  Result.FValue := TEncoding.UTF8.GetBytes(Value);
end;

class operator TPassphrase.Implicit(const Value: TBytes): TPassphrase;
begin
  Result.FType := ptPassword;
  Result.FValue := Value;
end;

constructor TPassphrase.Create(const Key, InitVector: TBytes);
begin
  FType := ptKeys;
  FKey := Key;
  FInitVector := InitVector;
end;

constructor TPassphrase.Create(const Password: string; Encoding: TEncoding);
begin
  FType := ptPassword;
  FValue := Encoding.GetBytes(Password);
end;

使用如下:

var
  Password: TBytes


FCipher.Passphrase:=Password;  

//以上调用 class operator Implicit(const Value: TBytes): TPassphrase;

       

内联函数(Inlining) D7的inline关键字作为保留字并不会对编译器产生实际作用,在2009此关键字起到内嵌到代码起到实际作用。语法如下: function foo: Integer; inline; 内部函数/过程也可以使用,但在D2009测试版,类方法的内部函数使用inline后不认Self指针;类的子过程/子函数,也可以使用inline关键字,但没有实际效果,且虚方法/继承方法(virtual/override)不能使用。 重载运算符(Operator Overloading) 可以重载部分运算符,如+、-、类型转换等,在D2006只支持到record,但从2007开始支持到Class,以下示例修改自官网: TMyClass = class // Addition of two operands of type TMyClass class operator Add(a, b: TMyClass): TMyClass; // Subtraction of type TMyClass class operator Subtract(a, b: TMyClass): TMyclass; // Implicit conversion of an Integer to type TMyClass class operator Implicit(a: Integer): TMyClass; // Implicit conversion of TMyClass to Integer class operator Implicit(a: TMyClass): Integer; // Explicit conversion of a Double to TMyClass class operator Explicit(a: Double): TMyClass; end; class operator TMyClass.Add(a, b: TMyClass): TMyClass; begin //... end; var x, y: TMyClass begin x := 12; // Implicit conversion from an Integer y := x + x; // Calls TMyClass.Add(a, b: TMyClass): TMyClass end; 类助手(Class Helpers) Helper是对原Class的扩展,是我们在不修改原类的基础上增加类方法,并加入原类的空间。在Delphi,对对象的调用实际上采用了两个步骤,首先是把对象地址放入eax寄存器,然后call类方法,所以如果不使用继承类增加数据的话,用父类调用继承类的方法是没问题的,所以其实这样的方法在D7也可以使用,但却很麻烦。所以Class Helper起到的就是这个作用,在Class Helper可以增加的就是与实例无关的内容,所以任何需要增加实例Size的活VMT的功能不能声明,例如变量、虚方法等,但只占用类空间的没关系,如class var。在应用上我们可以通过这种方法方便的给VCL一类控件加上某个属性。 TFoo = class helper for TControl private function GetA: Integer; public class var X: Integer; procedure MSG(var Message: TMessage); message WM_MYMESSAGE; procedure ProcFoo; property A: Integer read GetA; end; // ... procedure TForm1.Foofoo; begin ProcFoo; // TControl -> TWinControl -> TScrollingWinControl-> TCustomForm -> TForm -> TFrom1: Call TFoo.ProcFoo end; strict关键字(Keyword “strict”) 众所周知,在Delphi,类的private和protected域的变量可以被同一单元可以自由的被访问(Delphi的类没有“友元”的概念,但同一个unit可以说自动友元化了),而并非是真正的私有或只能被继承类访问。而strict关键字的作用就是使该内容变成严格OO意义上的private/protected作用域,这点没有什么多说的。语法: strict private // Blah... strict protected // Blah... 结构方法(Records with Methods) 也没什么特别的,就是和class差不多,就一个不用创建和销毁、不能继承、没有作用域之类的类,很容易掌握,所以这里就不多介绍了。但是很有意思的是带参数的constructor可以通过编译,可能是为了初始化的方便吧。 抽象类和固实类(Abstract and Sealed Classes) 这两个概念在OO也并不陌生,抽象类是不应该创建实例的(但D2006起的编译器就不给检查,连个Warning都没有,这还有啥用啊 -.- ),而固实类是不能被继承的。语法: TAnAbstractClass = class abstract // or (TParentClass) // Blah... end; TASealedClass = class sealed(TAnAbstractClass) // or empty // Blah... end; 类常量、类变量、类属性与静态类方法(Class const/var/property and Static Class Methods) 老的Delphi只提供了类方法,而没有提供类变量、类常量和类属性,这真的是很不方便。这里先区分一下我所使用的类(Class)和对象(Object)即类的实例(Instance of Class)。当在Delphi声明一个类的时候,这个类是有实际地址的,该地址记录了许多类的相关信息,比如实例的Size啊、虚方法信息啊一堆东西,而创建一个对象的时候则把类实例化,在堆(Heap)分配一块地址,包括内部数据和VMT之类的东西。在调用实例的时候,首先要知道对象地址,然后才能访问内部变量和调用方法时使用Self指针即实例地址;而在调用类方法的时候,eax的并不是实例的地址而是类的地址,然后再call方法,这时的Self指针并非实例地址而是类地址。所以对于每一个类和继承类来说,包括它和它的继承类的所有实例,类变量、常量都是同一个,这样就存在了一个唯一的可供使用的变量或常量,方便同步并且不需要使用较多的内存(可以参考C#的类,不过C#不允许从实例直接访问类变量、常量、方法)。而静态类方法则是在使用这个类方法的时候不传入class地址,也就是说没有Self指针,这样的类方法的访问开销要小于普通的类方法;这自然也就意味着,该类方法不能被继承(不能virtual/override)。另外,类属性的get/set方法必须使用静态类方法。 TFooClass = class private class procedure SetFoo(const Value: Integer); static; // A Static Class Method protected class var FX : Integer; // class var public const FC: Integer = 10; // class const class procedure VirtualProc; virtual; class property X: Integer read FX write FX; // class property class property Foo: Integer read FC write SetFoo; end; 类内部类型与嵌套类(Class Types and Nested Classes) 可以说现在的Class的域几乎相当于原来的整个unit,以前不能放里面的元素现在都可以放里面了,这个也没什么好多说的,试验一下就很容易明白了。 终方法(Final Methods) 这个也是建立在虚方法的基础上的,在override后使用final关键字,则表示该虚方法不能再被子类继承下去了。 TAClass = class public procedure Foo; virtual; end; TFinalMethodClass = class(TAClass) public procedure Test; override; final; // A Final Method end; For-in循环(For-in Loop) 这个应该是受.Net影响吧,支持遍历一个数组或提供了GetEnumerator函数的类。GetEnumerator要求返回一个类的实例,该类包含有Current属性和MoveNext方法。 procedure Foo(List: TStrings); i : Integer; lst : array[0..100]of Integer; s : string; begin for i in lst do ; for s in List do ; // Support of TStrings.GetEnumerator end;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海纳老吴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值