简体   繁体   English

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

[英]How to overload Inc (Dec) operators in Delphi?

Delphi documentation says that it is possible to overload the Inc and Dec operators; Delphi文档说可能会使Inc和Dec运算符超载; I see no valid way to do it. 我认为没有有效的方法可以做到这一点。 Here are attempts to overload the Inc operator; 以下是尝试重载Inc运算符; some attempts lead to compile errors, some to runtime access violation (Delphi XE): 一些尝试导致编译错误,一些尝试导致运行时访问冲突(Delphi XE):

program OverloadInc;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TMyInt = record
    FValue: Integer;
//    class operator Inc(var A: TMyInt);   DCC error E2023
    class operator Inc(var A: TMyInt): TMyInt;
    property Value: Integer read FValue write FValue;
  end;

class operator TMyInt.Inc(var A: TMyInt): TMyInt;
begin
  Inc(A.FValue);
  Result:= A;
end;

type
  TMyInt2 = record
    FValue: Integer;
    class operator Inc(A: TMyInt2): TMyInt2;
    property Value: Integer read FValue write FValue;
  end;

class operator TMyInt2.Inc(A: TMyInt2): TMyInt2;
begin
  Result.FValue:= A.FValue + 1;
end;

procedure Test;
var
  A: TMyInt;

begin
  A.FValue:= 0;
  Inc(A);
  Writeln(A.FValue);
end;

procedure Test2;
var
  A: TMyInt2;
  I: Integer;

begin
  A.FValue:= 0;
//  A:= Inc(A);  DCC error E2010
  Writeln(A.FValue);
end;

begin
  try
    Test;     // access violation
//    Test2;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

The signature of the operator is wrong. 运营商的签名是错误的。 It should be: 它应该是:

class operator Inc(const A: TMyInt): TMyInt;

or 要么

class operator Inc(A: TMyInt): TMyInt;

You cannot use a var parameter. 您不能使用var参数。

This program 这个计划

{$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.

produces this output: 产生这个输出:

1

Discussion 讨论

This is a rather unusual operator when overloaded. 当超载时,这是一个相当不寻常的操作员。 In terms of usage the operator is an in-place mutation. 在使用方面,操作员是就地突变。 However, when overloaded, it works like an addition operator with an implicit addend of one. 但是,当重载时,它的作用类似于加法运算符,其隐式加数为1。

So, in the code above this line: 所以,在这行上面的代码中:

Inc(A);

is effectively transformed into 有效地转化为

A := TMyInt.Inc(A);

and then compiled. 然后编译。

If you are wanting to maintain true in-place mutation semantics, and avoid the copying associated with this operator, then I believe that you need to use a method of the type. 如果您想要保持真正的就地变异语义,并避免与此运算符关联的复制,那么我相信您需要使用该类型的方法。

procedure Inc; inline;
....
procedure TMyInt.Inc;
begin
  inc(FValue);
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM