1.函數的定義
//格式
function functionName(parameterList): returnType; directives;
localDeclarations;
begin
statements
end;
//例1
function WF: Integer;
begin
WF := 17;
end;
//例2
function WF: Integer;
begin
Result := 17;
end;
//例3 function MyFunction: Integer;
begin
MyFunction := 5;
Result := Result * 2;
MyFunction := Result + 1;
end;
2.調用方式
Delphi的函數有幾種調用方式,
Directive Parameter order Clean-up Passes parameters in registers? register Left-to-right Routine Yes pascal Left-to-right Routine No cdecl Right-to-left Caller No stdcall Right-to-left Routine No safecall Right-to-left Routine No例如:
function MyFunction(X, Y: Real): Real; cdecl;
3.函數聲明
//先聲明後實現
function Calculate(X, Y: Integer): Real; forward;
function Calculate;
... { declarations }
begin
... { statement block }
end;
//擴展聲明
//1
function printf(Format: PChar): Integer; cdecl; varargs;
//2 Linking to Object Files
{$L BLOCK.OBJ}
procedure MoveWord(var Source, Dest; Count: Integer); external;
procedure FillWord(var Dest; Data: Integer; Count: Integer); external;
//3 Importing Functions from Libraries
function SomeFunction(S: string): string; external 'strlib.dll';
//The following declaration imports a function from user32.dll (part of the Win32 API).
function MessageBox(HWnd: Integer; Text, Caption: PChar; Flags: Integer): Integer; stdcall; external 'user32.dll' name 'MessageBoxA';
4.函數重載
function Divide(X, Y: Real): Real; overload;
begin
Result := X/Y;
end
function Divide(X, Y: Integer): Integer; overload;
begin
Result := X div Y;
end;