缺省值参数是在Dephi 4中被引进的(当调用有缺省值参数的过程和函数时,可以不提供参数)。为了声明一个有缺省值参数的过程或函数,在参数类型后跟一个等号和缺省值,示例如下:
Procudure HasDefVal(S:String;I:Integer=0);
HasDefVal()过程能用两种方式调用。
第一种方式:两个参数都指定:
HasDefVal(‘Hello’,26);
第二种方式:指定一个参数S,对I则用缺省值:
HasEelVal(‘hello’);//对于I,使用缺省值
在使用缺省值参数时要遵循下列几条规则:
1.有缺省值的参数必须在参数列表的最后。在一个过程或函数的参数列表中,没有缺省值的参数不能在有缺省值的参数后面。
2.有缺省值的参数必须是有序类型、指针类型、集合类型。
3.有缺省值的参数必须是数值参数或常量参数,不能是引用(Out)参数或无类型参数。
有缺省值参数的最大好处是,在想一个已存在的过程和函数增加功能时,不必关心向后兼容的问题,
例如:假定在一个单元中有个函数为AddInts(),它将两个数相加。
Function AddInts(I1,I2 : integer):integer;
begin
Result:= I1 + I2;
end;
如果想修改这个函数的功能使它能实现三个数相加,可能感到麻烦,因为增加一个参数将导致已经调用该函数的代码不能编译。由于有了有缺省值的参数,能扩展AddInts()函数的功能而不必担心它的兼容性,示例如下:
Function AddInts(I1,I2 :integer; I3: integer =0);
begin
Rusult := I1 + I2 + I3;
end;
范例:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation function AddInt(I1,I2 : Integer ;I3:Integer=0):integer; begin Result := I1+I2+I3; end; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(IntToStr(AddInt(1,2))); end; procedure TForm1.Button2Click(Sender: TObject); begin ShowMessage(IntToStr(AddInt(1,2,3))); end; end.