Overload Add operator for three extended records
Delphi 2006 introduced operator overloading which was then bugfixed in Delphi 2007. This is about Delphi 2007.
Why does the following 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 have declared an operator that adds two operands a of type TFirstRec and b of type TSecondRec resulting in a TThirdRec, I would have expected this to compile.
(If you need something less abstract, think of TMyDate, TMyTime and TMyDateTime.)
When I tried to compile the code in Delphi 2009 I have got the compiler error
[Pascal Error] Project1.dpr(21): E2518 Operator 'Add' must take least one 'TThirdRec' type in parameters
at line
class operator Add(_a: TFirstRec; _b: TSecondRec): TThirdRec;
so the answer is - at least one of the arguments (_a; _b) must be of type TThirdRec
Serg is right. This does compile:
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.
That can be a problem if you have to declare Add for all possible combinations of TFirstRec, TSecondRec and TThirdRec, as there is no forward declaration for records in Delphi.
精彩评论