gpt4 book ai didi

delphi - 如何为相互依赖的记录定义隐式转换运算符?

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

我在 Delphi 2006 中对记录使用运算符重载。(请不要告诉我不要回答这个问题。)

我有两种记录类型,其中隐式运算符重载。它们都只在模块的实现中,不通过接口(interface)暴露。

我的问题是,既然它们是相互依赖的,我不知道如何将第二种类型的声明转发给编译器。我知道如何处理函数、过程和类,但不知道如何处理记录。

这是我正在尝试做的一个简化示例:

implementation

type
TMyRec1 = record
Field1 : Integer;
class operator Implicit(a: TMyRec2): TMyRec1; // <---- Undeclared Identifier here.
end;

TMyRec2 = record
Field2: Integer;
class operator Implicit(a: TMyRec1): TMyRec2;
end;

class operator TMyRec1.Implicit(a:TMyRec2): TMyRec1;
begin
Result.Field1 := a.Field2;
end;

class operator TMyRec2.Implicit(a:TMyRec2): TMyRec2;
begin
Result.Field2 := a.Field1;
end;

最佳答案

您不能有记录类型的前向声明。定义两个 Implicit第二种类型的运算符:

type
TMyRec1 = record
Field1 : Integer;
end;

TMyRec2 = record
Field2: Integer;
class operator Implicit(a: TMyRec2): TMyRec1;
class operator Implicit(a: TMyRec1): TMyRec2;
end;

引自 the help :

Implicit conversions should be provided only where absolutely necessary, and reflexivity should be avoided. It is best to let type B implicitly convert itself to type A, and let type A have no knowledge of type B (or vice versa).

关于delphi - 如何为相互依赖的记录定义隐式转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206352/

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