Delphi类程序重载

RBA*_*RBA 0 delphi delphi-xe

考虑以下代码:

  TForm3 = class(TForm)
  public
   class procedure GetAConn(var res:String); overload;
   class procedure GetAConn(var res:Integer);overload;
    { Public declarations }
  end;

class procedure TForm3.GetAConn(var res: String);
begin
 showmessage(res);
end;

class procedure TForm3.GetAConn(var res: Integer);
begin
 showmessage(IntToStr(res))
end;
Run Code Online (Sandbox Code Playgroud)

编译没有任何问题.

现在,如果我这样做:

procedure TForm3.FormCreate(Sender: TObject);
begin
 TForm3.GetAConn('aaa');
 TForm3.GetAConn(10);
end;
Run Code Online (Sandbox Code Playgroud)

我得到[DCC错误] Unit3.pas(64):E2250没有可以使用这些参数调用的'GetAConn'的重载版本.

在Delphi XE中我没有发现有关此限制的内容.

LE:正在以这种方式工作:

class procedure TForm3.GetAConn(var res: String);
begin
 res := res + 'modif';
end;

class procedure TForm3.GetAConn(var res: Integer);
begin
 res := res + 100;
end;
procedure TForm3.FormCreate(Sender: TObject);
var s:String;
    i:Integer;
begin
 s:='aaa';
 TForm3.GetAConn(s);
 showmessage(s);
 i:=10;
 TForm3.GetAConn(i);
 showmessage(IntToStr(i))
end;
Run Code Online (Sandbox Code Playgroud)

Uli*_*rdt 6

通过引用传递参数.放弃var所有应该是好的:

class procedure GetAConn(const res: String); overload;
class procedure GetAConn(res: Integer); overload;
Run Code Online (Sandbox Code Playgroud)

(因为你不修改字符串参数我建议将其作为传递const.)

当然,如果你确实需要参考参数,那么你就无法传递文字或常量.但这与使用无关overload.(除了重载会混淆错误消息的事实.)

  • 您更喜欢"字符串"的主要原因是避免与托管类型的值传递相关联的开销.令人遗憾的是,特定的性能考虑因素与参数语义相混淆. (3认同)