運算符重載一直是個爭議的話題,.其實運算符重載就是方便我們而已,不用不會死人,用了方便點兒而已.D7之後的版本也支持運算符重載.我們來看個例子:
如果我們想2個結構體可以相加,比如說 a,b:TPoint;C:=a+b;是吧,多美好的事情呀.
01 THuangJacky = record
02 A,B,C:Integer;
03 //+
04 class Operator Add(a, b: THuangJacky): THuangJacky;
05 //=
06 class Operator Equal(a,b: THuangJacky):Boolean;
07 end;
08 var
09 Form1: TForm1;
10 implementation
11 {$R *.dfm}
12 { TH }
13 class Operator THuangJacky.Add(a, b: THuangJacky): THuangJacky;
14 begin
15 Result.A:=a.A + a.A;
16 Result.B:=a.B + b.B;
17 Result.C:=a.C + b.C;
18 end;
19 class Operator THuangJacky.Equal(a, b: THuangJacky): Boolean;
20 begin
21 if (a.A=b.A)and(a.B=b.B)and(a.C=b.C) then
22 Result:=True
23 else
24 Result:=False;
25 end;
26 procedure TForm1.btn1Click(Sender: TObject);
27 var
28 a,b,c:THuangJacky;
29 begin
30 a.A:=5;a.B:=6;a.C:=7;
31 b.A:=2;b.B:=3;b.C:=4;
32 //這就是好處
33 c:=a+b;
34 ShowMessageFmt('%D,%D,%D',[c.A,c.B,c.C]);
35 if not (a=b) then
36 ShowMessage('not equal');
37 end;
我們這裡的結構體就可以直接+ 和 = 判斷了,方便了那些搞算法的人.哈哈.下面附上所有的運算符:
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
BitwiseNot Unary BitwiseNot(a: type): resultType; not
Trunc Unary Trunc(a: type): resultType; Trunc
Round Unary Round(a: type): resultType; Round
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): resultType; >=
LessThan Comparison LessThan(a: type; b: type): resultType; <
LessThanOrEqual Comparison LessThanOrEqual(a: type; b: type): resultType; <=
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
我是DH,今天就說到這裡.