【发布时间】: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