微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中提供,偶尔阅读一下,以便重新了解运算符重载的可用内容.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐