【问题标题】:How to overload Inc (Dec) operators in Delphi?如何在 Delphi 中重载 Inc (Dec) 运算符?
【发布时间】:2016-01-02 23:58:24
【问题描述】:

Delphi documentation 表示可能会重载 Inc 和 Dec 运算符;我认为没有有效的方法来做到这一点。以下是重载 Inc 运算符的尝试;一些尝试导致编译错误,一些导致运行时访问冲突(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.

【问题讨论】:

    标签: delphi operator-overloading increment


    【解决方案1】:

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

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

    class operator Inc(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

    讨论

    重载时这是一个相当不寻常的运算符。在使用方面,运算符是就地突变。然而,当重载时,它就像一个隐含加数为 1 的加法运算符。

    所以,在这行上面的代码中:

    Inc(A);
    

    被有效地转化为

    A := TMyInt.Inc(A);
    

    然后编译。

    如果您想保持真正的就地突变语义,并避免与此运算符相关的复制,那么我相信您需要使用该类型的方法。

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

    【讨论】:

    • const 参数的突变看起来很奇怪,不是吗?还有返回值的函数原型被忽略?
    • 在调用点看起来像是突变,但是编译器将Inc(MyInt)翻译成MyInt := TMyInt.Inc(MyInt);是的,这很奇怪。我不会超载IncDec
    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2013-08-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多