Delphi 函数的重载和作用域

1.在delphi 中,我们可以使用相同的函数名来调用不同的函数,我们称这个函数为重载,函数的参数类型和参数的个数可以不同,用到的关键字overload;格式如下:

function addInt(x,y:integer):string;overload;
begin
  result := intToStr(x + y);
end;

function addInt(x,y,z:integer):string;overload;
begin
  result := intToStr(x + y + z);
end;

function addInt(x,y:integer;z:string):string;overload;
begin
  result := intToStr(x + y + strToInt(z));
end;

注意点:每个函数后面都需要加上:overload;

2.函数的作用域(局部和全局函数):

在单位文件下声明的函数只能应用于本单元,可以通过其他单元引用来使用函数;但是必须在被引用单位的接口部分声明函数,否则还是无法找到

如:

Unit1.pas文件

unit Unit1;

interface

uses
  windows, Messages, SysUtils;

uses 
  unit2;  //可以和上面的uses一起连写

implementation

procedure TForm1.Button1Click(Sender : TOBJect);
begin
  showmessage(addint(1,2,3));
end;

end.

Unit2.pas文件:

unit Unit2;
interface

uses
  windows, Messages, SysUtils;

function addint(x,y,z:Integer):string;  //必须在这里声明函数,才能被其他单位去引用

implementation

function addInt(x,y,z : integer):string;
begin
  Result := intToStr(x+y+z);
end;

end.
posted @ 2014-12-16 20:38  delphiclub  阅读(1233)  评论(0编辑  收藏  举报