delphi 三种变量:全局变量,类变量,局部变量

通常按照变量声明的范围,可以分为:全局变量,类变量,局部变量。

  全局变量:是指在类外声明的变量,通常这种变量时在整个工程内有效的,也就是说在整个工程中的类都可以使用。该变量的生存周期是在工程创建时有效,工程销毁时销毁。

  类变量:是指在类中声明的变量,这种变量在类中的方法都可以使用。其生命周期是在类创建时有效,类销毁时销毁。

  局部变量:是指在方法内部声明的变量,这种变量只能在方法内部使用。其生命周期也是在方法内部有效,当方法调用结束后,其内部所声明的变量也随之销毁。

正确声明3种变量的代码如下:

  TForm1=Class(TForm)

  Edit1 : TEdit;

  Label1 : TLabel;

  Button1 : TButton;

  Button2 : TButton;

  Button3 : Tbutton;

  procedure Button1Click(Sender : TObject);

  procedure Button2Click(Sender : TObject);

  procedure Button3Click(Sender : TObject);

  private

   {Private declarations}

   Name : String; //类变量;

  public

  {Public declarations}

  end;

Var

  Form1 : TForm;

  Name : String;//全局变量。

//在implementation之上定义为全局都可以看见

implementation

//在implementation之下定义为本单元看见

  {$R *.dfm}

 procedure TForm1.Button1Click(Sender : TObject);

 var

  Name : String; //局部变量;

 begin

   Name := '局部变量';

   Edit1.Text := Name;

 end;

end.