如何为互相依赖的记录定义隐式转换运算符? [英] How do I define implicit conversion operators for mutually dependent records?
问题描述
我在Delphi 2006中使用操作符重载记录(请不要回答这个问题,告诉我不要。)
I am using the operator overloading for records in Delphi 2006. (Please don't answer this question by telling me not to.)
我有两种记录类型其中隐式运算符重载。它们只是在实现模块的同时,不通过接口暴露出来。
I have two record types with the implicit operator overloaded. They are both only in the implementation of the module, not exposed through the interface.
我的问题是,现在他们是相互依赖的,我不知道如何将第二个类型声明为编译器。我知道如何使用函数,过程和类,但不能使用记录。
My problem is, now that they are mutually dependent, I don't know how to forward declare the second type to the compiler. I know how to do this with functions, procedures, and classes, but not with records.
这是一个简单的例子,我正在尝试:
Here is a simplified example of what I am trying to do:
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;
推荐答案
您不能对记录类型有转发声明。定义第二种类型的隐式
运算符:
You can't have forward declarations for record types. Define both Implicit
operators in the second type:
type
TMyRec1 = record
Field1 : Integer;
end;
TMyRec2 = record
Field2: Integer;
class operator Implicit(a: TMyRec2): TMyRec1;
class operator Implicit(a: TMyRec1): TMyRec2;
end;
从帮助:
隐式只有在绝对必要的时候才应提供转换,应避免反身。最好让类型B隐式地将其自身转换为类型A,而类型A不知道类型B(反之亦然)。
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).
这篇关于如何为互相依赖的记录定义隐式转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!