在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
其实 Delphi 2006 就已经支持运算符重载了, 不过 for Win32 的版本只是在 record 里支持. 先按 "你们两个谁的年龄大?" 写出原始例子吧: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} type TMyRec = record name: string; age: Word; end; procedure TForm1.Button1Click(Sender: TObject); var r1,r2: TMyRec; str: string; begin r1.name := '张三'; r1.age := 18; r2.name := '李四'; r2.age := 81; if r1.age > r2.age then str := r1.name else str := r2.name; ShowMessageFmt('%s年龄大', [str]); {李四年龄大} end; end.
type TMyRec = record name: string; age: Word; class operator GreaterThan(a,b: TMyRec): Boolean; end;
class operator TMyRec.GreaterThan(a,b: TMyRec): Boolean; {注意复制后再加上方法名: "TMyRec."} begin Result := a.age > b.age; end;
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} type TMyRec = record name: string; age: Word; class operator GreaterThan(a,b: TMyRec): Boolean; end; class operator TMyRec.GreaterThan(a,b: TMyRec): Boolean; begin Result := a.age > b.age; end; procedure TForm1.Button1Click(Sender: TObject); var r1,r2: TMyRec; str: string; begin r1.name := '张三'; r1.age := 18; r2.name := '李四'; r2.age := 81; if r1 > r2 then str := r1.name else str := r2.name; ShowMessageFmt('%s年龄大', [str]); {李四年龄大} end; end.
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论