1. 程式人生 > >Delphi 過程與函式

Delphi 過程與函式

delphi分為過程和函式:

delphi 過程以保留字procedure開始,沒有返回值;函式以保留字function開始,有返回值。

  一:  過程的框架:

Procedure 過程名([形參列表])// 引數可選
var
      //宣告常量、變數或另一個過程或函式等
begin
      語句; 
end;

 介面如圖所示:

執行前:

程式碼如下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Myproc(Str: String);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  x: String;
begin
  x:= Edit1.Text;
  Myproc(x);
end;

procedure TForm1.Myproc(Str: String);
begin

    ShowMessage(Str)//就是彈出一個視窗

end;

end.

 執行後:

二:函式的框架:

Function 函式名(形參表): 返回值型別;
       區域性宣告
begin
       語句;
end;

 function 例項:

 

 程式碼如下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    procedure Button1Click(Sender: TObject);
    function add(num1 :Integer;num2 :Integer) :Integer;//定義加法
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  add(1,2);
end;

function TForm1.add(num1 :Integer;num2 :Integer) :Integer;//函式的具體描述
var
    sum:Integer;
begin
    sum:=num1+num2;
    Edit1.Text:=inttostr(sum);
end;
end.

 執行結果: