第一种定义方法:
private
{ Private declarations }
times:integer;
第二种定义方法:
procedure TForm1.Button1Click(Sender: TObject);
var
passfile:textfile;
passstr:string;
times:=times+1;
begin
{************}
end;
这两种定义有什么不同?
在以下代码中第一种定义可行,第二种定义不能正确判断登录的次数.
以下的全部代码:
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
times:integer;
public
{ Public declarations } end;var
Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
var
passfile:textfile;
passstr:string;
begin
assignfile(passfile,'c:\password\master.txt');{将文件变量与密码文件联系起来}
reset(passfile);
readln(passfile,passstr);
closefile(passfile);
times:=times+1;
if edit1.Text=passstr then
ShowMessage('ok')
else
begin
if MessageDlg('密码输入错误,是否退出?',mtConfirmation,[mbYes,mbNo],0)=mryes then
close
else if times<5 then
edit1.SetFocus
else
begin
MessageDlg('对不起,密码输入错误达到5次!请退出.',mtInformation,[mbOk],0);
application.Terminate;
end;
end;
end;end.
private
{ Private declarations }
times:integer;
第二种定义方法:
procedure TForm1.Button1Click(Sender: TObject);
var
passfile:textfile;
passstr:string;
times:=times+1;
begin
{************}
end;
这两种定义有什么不同?
在以下代码中第一种定义可行,第二种定义不能正确判断登录的次数.
以下的全部代码:
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
times:integer;
public
{ Public declarations } end;var
Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
var
passfile:textfile;
passstr:string;
begin
assignfile(passfile,'c:\password\master.txt');{将文件变量与密码文件联系起来}
reset(passfile);
readln(passfile,passstr);
closefile(passfile);
times:=times+1;
if edit1.Text=passstr then
ShowMessage('ok')
else
begin
if MessageDlg('密码输入错误,是否退出?',mtConfirmation,[mbYes,mbNo],0)=mryes then
close
else if times<5 then
edit1.SetFocus
else
begin
MessageDlg('对不起,密码输入错误达到5次!请退出.',mtInformation,[mbOk],0);
application.Terminate;
end;
end;
end;end.
第二种定义的变量为‘局部变量’。它只在局部的方法中存在,超脱这个方法后,在其它地方无法进行引用。
因此,楼主应该用第一种方法来定义变量。因为如果将times定义在过程中的话,你每一次点击button1都会重新为times赋值。
不过别忘了,命名多的时候别重复了啊,到时候单元变量也变了,HOHO