Recent

Author Topic: Problem with operator overrides  (Read 1460 times)

liewald

  • Full Member
  • ***
  • Posts: 142
Problem with operator overrides
« on: February 11, 2019, 12:10:30 pm »
Lazarus 1.8.2 r57375 FPC 3.0.4 x86_64-linux-gtk2

I'm translating some Delphi code over to Lazarus and I'm getting a syntax error on an operator override but cant spot whats wrong...

Quote

 TPoint2px = record
  x, y: Integer;

{$ifdef fpc}
operator + (const a, b: TPoint2px) c: TPoint2px;
{$endif} 

{$ifdef fpc}
operator + (const a, b: TPoint2px) c: TPoint2px;
{$else}
class operator TPoint2px.Add(const a, b: TPoint2px): TPoint2px;
{$endif}
begin
 Result.x:= a.x + b.x;
 Result.y:= a.y + b.y;
end;


this is failing  on "operator + (const a, b: TPoint2px) c: TPoint2px;"  with " Fatal: Syntax error, "=" expected but "+" found"

any Ideas/Guidance would be greatly appreciated

Dave

Thaddy

  • Hero Member
  • *****
  • Posts: 14210
  • Probably until I exterminate Putin.
Re: Problem with operator overrides
« Reply #1 on: February 11, 2019, 12:17:11 pm »
Such operators do not work in mode delphi. Use mode objfpc. But the delphi code should work in mode delphi, so simply leave out the + overload will work.
Simply use class operator TPoint2px.Add(const a, b: TPoint2px): TPoint2px; and use mode delphi.
Alternatively class operator TPoint2px.+(const a, b: TPoint2px): TPoint2px; in mode objfpc should work, provided {$modeswitch advancedrecords} is active.
So:
Code: Pascal  [Select][+][-]
  1. {$ifdef fpc}
  2. class operator + (const a, b: TPoint2px) c: TPoint2px; //when using mode objfpc
  3. {$else}
  4. class operator TPoint2px.Add(const a, b: TPoint2px): TPoint2px; //when using mode delphi
  5. {$endif}
  6. begin
  7.  Result.x:= a.x + b.x;
  8.  Result.y:= a.y + b.y;
  9. end;
  10.  

« Last Edit: February 11, 2019, 01:02:04 pm by Thaddy »
Specialize a type, not a var.

PascalDragon

  • Hero Member
  • *****
  • Posts: 5446
  • Compiler Developer
Re: Problem with operator overrides
« Reply #2 on: February 11, 2019, 04:10:36 pm »
@Thaddy: It should be
Code: Pascal  [Select][+][-]
  1. class operator TPoint2px.+(const a, b: TPoint2px): TPoint2px;
for mode ObjFPC as well if the operator is part of TPoint2px (note the added TPoint2px and the removed result variable name c).

But when porting code from Delphi one should use mode Delphi anyway...

 

TinyPortal © 2005-2018