delphi – 运算符不适用于此操作数类型

我有这种情况:

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;

有:

var
 awheel,bwheel: twheel;
begin
  try
    awheel := 'PA';
    bwheel := 'PA';
    if awheel = bwheel then writeln ('pippo');
end.

当我运行它时转向我这个错误

E2015 Operator not applicable to this operand type

我已经解决了写作:

if awheel = string(bwheel) then writeln ('pippo');

但是可以在没有添加字符串(…)的情况下解决它吗?在第一时刻,我认为是:

class operator Implicit(const Value: TWheel): Twheel;

但编译器给我错误,告诉我只接受一个TWheel类型.所以我想知道是否有解决方案,或者我是否需要使用带字符串(…)的转换类型?
非常感谢.

解决方法

您需要定义一个Equal运算符:

class operator Equal(const a,b: TWheel): Boolean;

我想实现应该是:

class operator TWheel.Equal(const a,b: TWheel): Boolean;
begin
  Result := a.FWheelEnum=b.FWheelEnum;
end;

您可能还想要实现NotEqual运算符.

class operator TWheel.NotEqual(const a,b: TWheel): Boolean;
begin
  Result := a.FWheelEnum<>b.FWheelEnum;//Could write not (a=b) instead
end;

事实上,这些运算符的定义足以让编译器接受与混合TWheel和字符串操作数的相等比较.

完整的运算符列表在documentation中提供,偶尔阅读一下,以便重新了解运算符重载的可用内容.

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...