如何在Delphi中重载指定运算符以进行记录

Art*_*tik 5 delphi operator-overloading assignment-operator

我想制作使用动态数组的记录类型.

使用这种类型的变量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)
Run Code Online (Sandbox Code Playgroud)

有两个问题:

  1. 当我不在我的TMyRec中使用覆盖赋值运算符时,A:= B表示A和B(它们的Inner_Array)指向内存中的相同位置.
  2. 避免问题1)我想重载赋值运算符使用:

    class operator TMyRec.Implicit(source:TMyRec):TMyRec;

但是编译器(Delphi XE)说:

[DCC错误]:E2521运算符'隐式'必须在参数或结果类型中采用一个'TMyRec'类型

如何解决这个问题.我在stackoverflow上阅读了几篇类似的帖子,但是在我的情况下它们不起作用(如果我理解的话).

ARTIK

Dav*_*nan 5

不能重载赋值运算符.这意味着您尝试做的事情是不可能的.

  • 可以在动态阵列上引入COW功能.这将在写入数组时处理克隆,就像`String`类型一样.它有点乱,但我设法让它工作.我将尽快发布代码.令我不安的主要问题是像SetLength`,`Length`等内在函数不能作为运算符重载引入. (2认同)