Overload Add statement for three extended entries

Delphi 2006 introduced operator overloading, which was later fixed in Delphi 2007. This applies to Delphi 2007.

Why the following does not compile:

type
  TFirstRec = record
    // some stuff
  end;

type
  TSecondRec = record
    // some stuff
  end;

type
  TThirdRec = record
    // some stuff
    class operator Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;
end;

class operator TThirdRec.Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;
begin
   // code to initialize Result from the values of _a and _b
end;

var
  a: TFirstRec;
  b: TSecondRec;
  c: TThirdRec;
begin
  // initialize a and b

  c := a + b; // <== compile error: "Operator not applicable to this operand type"
end.

Since I declared a statement that adds two operands a of type TFirstRec and b of type TSecondRec, which results in TThirdRec, I would expect this to compile.

(If you need something less abstract, think about TMyDate, TMyTime, and TMyDateTime.)

+3
source share
2 answers

When I tried to compile code in Delphi 2009, I got a compiler error

[ Pascal] Project1.dpr(21): E2518 "" "TThirdRec"

class operator Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;

- , (_a; _b) TThirdRec

+2
. :
program Project51;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TThirdRec = record
    // some stuff
  end;

  TFirstRec = record
    // some stuff
  end;

  TSecondRec = record
    // some stuff
    class operator Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;
  end;

class operator TSecondRec.Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;
begin
   // code to initialize Result from the values of _a and _b
end;

var
  a: TFirstRec;
  b: TSecondRec;
  c: TThirdRec;
begin
  // initialize a and b

  c := a + b; // <== compile error: "Operator not applicable to this operand type"
end.

, "" TFirstRec, TSecondRec TThirdRec, Delphi .

+1

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


All Articles