考虑一下这门课:
unit u_myclass;
interface
type
TMyClass = class
public
class function Foo : Integer;
function Foo : Integer;
end;
implementation
{ TMyClass }
class function TMyClass.Foo: Integer;
begin
Result := 10;
end;
function TMyClass.Foo: Integer;
begin
Result := 1;
end;
end.
我想使用同名的类函数和实例函数。不幸的是,Delphi不喜欢这样,编译器会阻止这些错误:
[DCC Error] u_myclass.pas(9): E2252 Method 'Foo' with identical parameters already exists
[DCC Error] u_myclass.pas(20): E2037 Declaration of 'Foo' differs from previous declaration
[DCC Error] u_myclass.pas(9): E2065 Unsatisfied forward or external declaration: 'TMyClass.Foo'
我的问题是:这是可能的还是简单的语言限制(我需要重命名这两种方法之一)?
发布于 2014-10-01 01:11:30
不可能为实例方法和类方法使用相同的名称。这是不允许的,这意味着编译器在某些情况下无法区分它们。
例如,如果您写:
procedure TMyClass.Bar;
begin
Foo;
end;
然后编译器无法确定您想要调用类方法还是实例方法。
发布于 2014-10-01 00:44:51
我找到的唯一解决方案是使用重载和不同的参数:
unit u_myclass;
interface
type
TMyClass = class
public
class function Foo(A : Integer) : Integer; overload;
function Foo : Integer; overload;
end;
implementation
{ TMyClass }
class function TMyClass.Foo(A: Integer): Integer;
begin
Result := A;
end;
function TMyClass.Foo: Integer;
begin
Result := 1;
end;
end.
https://stackoverflow.com/questions/26137157
复制相似问题