在delphi中怎么表示和使用静态的变量?

 在delphi中怎么表示和使用静态的变量?

来源:http://topic.csdn.net/t/20031211/14/2552688.html


答:在Delphi5中直接用const来定义静态局部变量,在Delphi6中则可以使用const和{$J+}开关来办到。但是这样的静态变量如果定义在类方法中,那么这个类所创建的对象里的静态变量都是共享的。

我写了一个简单的例程如下:

在Delphi里New-> Application,再New-> Unit,贴入MyObj类的代码如下:
unit   Unit2;

interface

type
    TMyObj   =   class
    public
        procedure   ShowID;
    end;

implementation

uses   Dialogs,   SysUtils;

procedure   TMyObj.ShowID;
{$J+}
const
    I:   Integer   =   0;
{$J-}
begin
    ShowMessage(IntToStr(I));
    Inc(I);
end;

end.


然后回到Unit1,在Interface段添加对Unit2的引用,在Form1上放2个Button。
为Form1的OnCreate、OnClose事件以及两个Button的OnClick事件添写处理代码,最终使Unit1的代码变成如下:

unit   Unit1;

interface

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

type
    TForm1   =   class(TForm)
        Button1:   TButton;
        Button2:   TButton;
        procedure   FormCreate(Sender:   TObject);
        procedure   Button1Click(Sender:   TObject);
        procedure   Button2Click(Sender:   TObject);
        procedure   FormClose(Sender:   TObject;   var   Action:   TCloseAction);
    private
        {   Private   declarations   }
        OBJ1,   OBJ2:   TMyObj;
    public
        {   Public   declarations   }
    end;

var
    Form1:   TForm1;

implementation

{$R   *.dfm}

{   TForm1   }

procedure   TForm1.FormCreate(Sender:   TObject);
begin
    OBJ1   :=   TMyObj.Create;
    OBJ2   :=   TMyObj.Create;
end;

procedure   TForm1.Button1Click(Sender:   TObject);
begin
    OBJ1.ShowID;
end;

procedure   TForm1.Button2Click(Sender:   TObject);
begin
    OBJ2.ShowID;
end;

procedure   TForm1.FormClose(Sender:   TObject;   var   Action:   TCloseAction);
begin
    OBJ1.Free;
    OBJ2.Free;
end;

end.

现在按F9运行程序,点击Button1-> 显示数字0-> 点击Button1-> 显示数字1-> 点击Button2-> 显示数字2,这表示OBJ1和OBJ2的静态局部变量I在整个类中是共享的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值