我希望使用动态数组来进行记录类型的操作。
使用此类型的变量A和B,我希望能够执行A:=B(和其他)操作,并且能够修改A的内容而不影响B,就像下面的代码片段一样:
type
TMyRec = record
Inner_Array: array of double;
public
procedure SetSize(n: integer);
class operator Implicit(source: TMyRec): TMyRec;
end;
implementation
procedure TMyRec.SetSize(n: integer);
begin
SetLength(Inner_Array, n);
end;
class operator TMyRec.Implicit(source: TMyRec): TMyRec;
begin
//here I want to copy data from source to destination (A to B in my simple example below)
//but here is the compilator error
//[DCC Error] : E2521 Operator 'Implicit' must take one 'TMyRec' type in parameter or result type
end;
var
A, B: TMyRec;
begin
A.SetSize(2);
A.Inner_Array[1] := 1;
B := A;
A.Inner_Array[1] := 0;
//here are the same values inside A and B (they pointed the same inner memory)
有两个问题:
1. 当我在TMyRec中不使用覆盖赋值操作符时,A:=B表示A和B(它们的Inner_Array)指向内存中相同的位置。
2. 为了避免问题1),我想使用以下方式重载赋值操作符:
class operator TMyRec.Implicit(source: TMyRec): TMyRec;
但编译器(Delphi XE)报错:
[DCC Error] : E2521 Operator 'Implicit' must take one 'TMyRec' type in parameter or result type 如何解决这些问题。 我在stackoverflow上读了几篇类似的帖子,但它们在我的情况下不起作用(如果我理解得正确的话)。
Artik
TMyRec.Clone
的函数。 - LU RDInner_Array
设为不可变的;像A.Inner_Array[1] := 1;
这样的代码将被禁止 - 对Inner_Array
的任何写入都应该创建一个新的数组实例。阅读 http://sergworks.wordpress.com/2013/04/10/on-the-operator-overloading-in-delphi/ 获取更多提示。 - kludg