Operator not applicable to this type of operand

I have this situation:

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; 

with:

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

When I started it, turn me this error:

 E2015 Operator not applicable to this operand type 

I decided to write:

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

but can you solve it without adding a line (...)? At the first moment, I came up with something like:

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

but the compiler will give me an error saying that only one type of TWheel is accepted. So I wanted to know if there is a solution for it, or do I need a conversion type with a string (...)? Thank you very much.

+4
source share
1 answer

You need to define an Equal statement:

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

I assume that the implementation should be:

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

You might also want to implement the NotEqual operator.

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

The definition of these operators is actually enough for the compiler to accept a comparison of equality with mixed operands TWheel and string .

The full list of operators is presented in the documentation , and it is worth reading once in a while to find out what is available in the way of operator overloading.

+7
source

Source: https://habr.com/ru/post/1383074/


All Articles