如何在Delphi中重载Inc(Dec)运算符?
说有可能使Inc和Dec运营商超载;我看不出有什么有效的办法。以下是试图使Inc运营商超载的尝试;有些尝试会导致编译错误,有些尝试会导致运行时访问冲突(Delphi XE):如何在Delphi中重载Inc(Dec)运算符?,delphi,operator-overloading,increment,Delphi,Operator Overloading,Increment,说有可能使Inc和Dec运营商超载;我看不出有什么有效的办法。以下是试图使Inc运营商超载的尝试;有些尝试会导致编译错误,有些尝试会导致运行时访问冲突(Delphi XE): 操作员的签名有误。应该是: class operator Inc(const A: TMyInt): TMyInt; 或 不能使用var参数 这个节目 {$APPTYPE CONSOLE} type TMyInt = record FValue: Integer; class operator In
操作员的签名有误。应该是:
class operator Inc(const A: TMyInt): TMyInt;
或
不能使用var
参数
这个节目
{$APPTYPE CONSOLE}
type
TMyInt = record
FValue: Integer;
class operator Inc(const A: TMyInt): TMyInt;
property Value: Integer read FValue write FValue;
end;
class operator TMyInt.Inc(const A: TMyInt): TMyInt;
begin
Result.FValue := A.FValue + 1;
end;
procedure Test;
var
A: TMyInt;
begin
A.FValue := 0;
Inc(A);
Writeln(A.FValue);
end;
begin
Test;
Readln;
end.
生成此输出:
1
有效地转化为
A := TMyInt.Inc(A);
然后编译
如果您希望维护真正的就地变异语义,并避免与此操作符相关联的复制,那么我相信您需要使用这种类型的方法
procedure Inc; inline;
....
procedure TMyInt.Inc;
begin
inc(FValue);
end;
常数参数的变异看起来很奇怪,不是吗?还有要忽略返回值的函数原型?它看起来像是调用站点上的变异,但编译器将
Inc(MyInt)
转换为MyInt:=TMyInt.Inc(MyInt)代码>是的,这很奇怪。我不会超载Inc
和Dec
。
Inc(A);
A := TMyInt.Inc(A);
procedure Inc; inline;
....
procedure TMyInt.Inc;
begin
inc(FValue);
end;