重载三个扩展记录的添加运算符
Delphi 2006 引入了运算符重载,然后在 Delphi 2007 中修复了错误。这是关于 Delphi 2007 的。
为什么以下内容无法编译:
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.
因为我已经声明了一个运算符,该运算符将 TFirstRec 类型的两个操作数 a 和 TSecondRec 类型的 b 相加,生成 TThirdRec,我本来希望这个能够编译。
(如果您需要不太抽象的东西,请考虑 TMyDate、TMyTime 和 TMyDateTime。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我尝试在 Delphi 2009 中编译代码时,出现编译器错误
[Pascal Error] Project1.dpr(21): E2518 Operator 'Add' must take at least one 'TThirdRec' type inparameters
at line
所以答案是 - 在至少一个参数 (_a; _b) 必须是 TThirdRec 类型
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
so the answer is - at least one of the arguments (_a; _b) must be of type TThirdRec
塞尔格是对的。这确实可以编译:
如果您必须为 TFirstRec、TSecondRec 和 TThirdRec 的所有可能组合声明 Add,那可能会出现问题,因为 Delphi 中没有记录的前向声明。
Serg is right. This does compile:
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.