Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Delphi中重载Inc(Dec)运算符?_Delphi_Operator Overloading_Increment - Fatal编程技术网

如何在Delphi中重载Inc(Dec)运算符?

如何在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

说有可能使Inc和Dec运营商超载;我看不出有什么有效的办法。以下是试图使Inc运营商超载的尝试;有些尝试会导致编译错误,有些尝试会导致运行时访问冲突(Delphi XE):


操作员的签名有误。应该是:

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;