技术交流,DH讲解
运算符重载一直是个争议的话题,.其实运算符重载就是方便我们而已,不用不会死人,用了方便点儿而已.D7之后的版本也支持运算符重载.我们来看个例子: 如果我们想2个结构体可以相加,比如说 a,b:TPoint;C:=a+b;是吧,多美好的事情呀.
THuangJacky = record
A,B,C:Integer;
//+
class operator Add(a, b: THuangJacky): THuangJacky;
//=
class operator Equal(a,b: THuangJacky):Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TH }
class operator THuangJacky.Add(a, b: THuangJacky): THuangJacky;
begin
Result.A:=a.A + a.A;
Result.B:=a.B + b.B;
Result.C:=a.C + b.C;
end;
class operator THuangJacky.Equal(a, b: THuangJacky): Boolean;
begin
if (a.A=b.A)and(a.B=b.B)and(a.C=b.C) then
Result:=True
else
Result:=False;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
a,b,c:THuangJacky;
begin
a.A:=5;a.B:=6;a.C:=7;
b.A:=2;b.B:=3;b.C:=4;
//这就是好处
c:=a+b;
ShowMessageFmt('%D,%D,%D',[c.A,c.B,c.C]);
if not (a=b) then
ShowMessage('not equal');
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,今天就说到这里.
|
请发表评论