8 delphi
这有效:
constructor TMyObj.Create;
begin
inherited;
end;
Run Code Online (Sandbox Code Playgroud)
为什么这也不起作用?
function TMyObjEx.Import(CONST FileName: string; CONST x, y, z: Integer): string;
begin
result:= inherited; // Import(FileName, x, y, z); <--- Compiler says: "incompatible types"
//do other stuff here
end;
Run Code Online (Sandbox Code Playgroud)
TMyObjEx的声明是这样的:
TYPE
TMyObj = class(TChObj)
private
protected
public
function Import (CONST FileName: string; CONST x, y, z: Integer): string; virtual;
end;
TMyObjEx= class(TMyObj)
private
protected
public
function Import(CONST FileName: string; CONST x, y, z: Integer): string; override;
end;
Run Code Online (Sandbox Code Playgroud)
Nic*_*ges 10
这是正确的答案.
正如您在上面提到的那样,正确的方法是:
function TMyObjEx.Import(CONST FileName: string; CONST x, y, z: Integer): string;
begin
result:= inherited Import(FileName, x, y, z);
//do other stuff here
end;
Run Code Online (Sandbox Code Playgroud)
语言不支持您希望这样做的方式.
所以最终回答你的问题"为什么这不起作用?" 是因为这不是语言的设计方式.
至于为什么不支持它,几年前哈尔瓦德在他的博客中写了一个似是而非的解释:
一个警告与"继承;" 语法是函数不支持它.对于函数,您必须使用显式语法,包括方法名称和任何参数.例如:
[部分代码]
这可能看起来像Delphi语言设计中的疏忽,但我认为这是故意的.它背后的基本原理可能是,如果TMyClass.MethodC是抽象的(或将来是抽象的),后代类中的Result赋值将被删除,因此Result突然未定义值.这肯定会导致微妙的错误.
起初我认为inherited如果您对函数的结果不感兴趣,您可以使用,但事实似乎并非如此。调用继承的函数方法需要方法名和参数。就是那样子。如果您传递的参数与当前方法接收的参数不同,或者您正在调用完全不同的方法,则还需要提及方法名称。