我有这种情况:
type
TWheel = record
private type
TWheelEnum = (whBA, whCA, whFI, whGE, whMI, whNA, whPA, whRM, whRN,
whTO, whVE);
var
FWheelEnum: TWheelEnum;
public
class operator Implicit(const Value: string): TWheel;
class operator Implicit(const Value: TWheel): string;
end;
Run Code Online (Sandbox Code Playgroud)
有:
var
awheel, bwheel: twheel;
begin
try
awheel := 'PA';
bwheel := 'PA';
if awheel = bwheel then writeln ('pippo');
end.
Run Code Online (Sandbox Code Playgroud)
当我运行它时转向我这个错误:
E2015 Operator not applicable to this operand type
Run Code Online (Sandbox Code Playgroud)
我已经解决了写作:
if awheel = string(bwheel) then writeln ('pippo');
Run Code Online (Sandbox Code Playgroud)
但是可以在没有添加字符串(...)的情况下解决它吗?在第一时刻,我认为是:
class operator Implicit(const Value: TWheel): Twheel;
Run Code Online (Sandbox Code Playgroud)
但编译器给我错误,告诉我只接受一个TWheel类型.所以我想知道是否有解决方案,或者我是否需要使用带字符串(...)的转换类型?非常感谢.
您需要定义一个Equal运算符:
class operator Equal(const a, b: TWheel): Boolean;
Run Code Online (Sandbox Code Playgroud)
我想实现应该是:
class operator TWheel.Equal(const a, b: TWheel): Boolean;
begin
Result := a.FWheelEnum=b.FWheelEnum;
end;
Run Code Online (Sandbox Code Playgroud)
您可能还想要实现NotEqual运算符.
class operator TWheel.NotEqual(const a, b: TWheel): Boolean;
begin
Result := a.FWheelEnum<>b.FWheelEnum;//could write not (a=b) instead
end;
Run Code Online (Sandbox Code Playgroud)
事实上,这些运算符的定义足以让编译器接受与混合TWheel和string操作数的相等比较.
文档中提供了完整的运算符列表,偶尔阅读一下,以便重新了解运算符重载的可用内容.