gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:59:53 25 4
gpt4 key购买 nike

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.

最佳答案

运算符(operator)签名错误。应该是:

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

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.

So, in the code above this line:

Inc(A);

有效地转化为

A := TMyInt.Inc(A);

然后编译。

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

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

关于delphi - 如何在Delphi中重载Inc(Dec)运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32963666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com