gpt4 book ai didi

Delphi记录拷贝构造函数

转载 作者:行者123 更新时间:2023-12-03 18:18:01 26 4
gpt4 key购买 nike

看这段代码:

type
TTest = record
a: integer;
pa: PInteger;
end;

procedure TForm1.Button1Click(Sender: TObject);
var a, b: ttest;
begin

memo1.Clear;

a.a := 5;
a.pa := @a.a;

Memo1.Lines.Add(a.a.ToString + ' - ' + (a.pa)^.ToString);

b := a;
b.a := 8;

Memo1.Lines.Add(b.a.ToString + ' - ' + (b.pa)^.ToString);

end;

输出如下:

5 - 5
8 - 5

这是正确的,但不是我所期望的。当我说 b := a 时,它将 a 的每个字段复制到 b 中。所以鉴于 a.pa := @a.a; 当然 b.pa 将与 a.pa 相同。

相反,我希望在调用 b := a 时,b.pa 指向 b.a 而不是 a.a。我怎样才能做到这一点?输出将是

5 - 5
8 - 8

在 C++ 中,有(深)复制构造函数可以解决这个问题。在 Delphi 中,这是一个不同的场景,但是否存在“等效”的东西?我在文档中看到了运算符重载列表,但找不到合适的列表。

最佳答案

我不知道您要实现什么目标,但也许某个函数可以提供帮助。复制按预期工作,不需要初始化 pa。限制是,您不能再设置 pa

program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

type
TTest = record
a: integer;
function pa: PInteger;
end;

var a, b: TTest;

function TTest.pa: PInteger;
begin
Result := @a;
end;

begin
a.a := 5;
// a.pa := @a.a; <- this is not needed anymore but also not possible

WriteLn(IntToStr(a.a) + ' - ' + IntToStr((a.pa)^));

b := a;
b.a := 8;

WriteLn(IntToStr(b.a) + ' - ' + IntToStr((b.pa)^));
ReadLn;
end.

关于Delphi记录拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852948/

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