程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> 在BCB中使用VCL控件數組1

在BCB中使用VCL控件數組1

編輯:關於C++

昨晚和網友邬彥華在OICQ上閒聊,他言及正在為朋友編一個游戲菜單,其中動態創建了一組按紐,最後卻無法釋放。他的實現方法如下:

for (int i=1;i<=ButtonCount;i++)
{
TSpeedButton *spdBtn=new TSpeedButton(this);
spdBtn->Parent=ScrollBox;//指定父控件
spdBtn->Caption=IntToStr(i);
spdBtn->Width=80;
spdBtn->Height=80;
spdBtn->OnClick=ButtonClick;
spdBtn->Left=intLeft;
spdBtn->Top=intTop;
spdBtn->GroupIndex=1;
spdBtn->Flat=true;
intLeft=intLeft+80+intSpace;
if (i%LineCount==0)
{
intTop=intTop+80+intSpace;
intLeft=intSpace;
}
buttons->Add(spdBtn);//buttons是一個TList的指針
}

最後用TList的Clear()方法無法釋放內存,

其實Clear()方法只是把List清空,要刪除還是得用delete,但是delete運算符必須要有刪除的指針,可這種實現方法無法得到指針!所以我就放棄了這種思路,忽然,電光一閃(不是要打雷了,而是我想出辦法來了),能不能用數組呢?說干就干!數組的分配?我想想,對!

TSpeedButton *Buttons[]=new TSpeedButton[4](this);

可是編譯器告訴我:ERROR!

TSpeedButton *Buttons[]=new TSpeedButton(this)[4]

還是錯!最後我利令智昏,把JAVA的分配方式都拿出來了:

TSpeedButton []*Buttons=new TSpeedButton[](this)

結果麼?不用說也知道!難道沒辦法了嗎?我想起了簡單類型的指針數組int x[]={1,2,3};於是就試

TSpeedButton *Buttons[]={new TSpeedButton(this),new TSpeedButton(this),new TSpeedButton(this)};

居然可以了!我正想得意的笑,忽然發現:如果要定義100個按鈕怎麼辦……打那麼一串重復的字誰受得了?就算是用COPY/PARST也難免要數錯,畢竟100次啊。難道就沒法子了?經過苦思冥想,又想起了一個辦法,一步一步的來怎麼樣?

TSpeedButton **button=new TButton*[100];

for(int i=0;i<100;i++)button[i]=new TSpeedButton(this);

哈哈!居然OK!再試試釋放:

for(int i=0;i<4;i++)delete x[i];

delete[]x;

哈哈!居然還是OK!於是我就寫了一例子:在一個窗口上放兩按紐,單擊可以顯示或關閉動態生成的按鈕。

首先聲明一個全局變量TButton **x;

然後在Button1的onClick中加入生成代碼:

x=new TButton*[4];
for(int i=0;i<4;i++)
{
x[i]=new TButton(this);
x[i]->Left=100;
x[i]->Top=10+i*30;
x[i]->Width=90;
x[i]->Height=25;
x[i]->Parent=this;
x[i]->Caption="按紐"+AnsiString(i);
}

單擊它就可以生成並顯示4個按鈕,然後在Button2加入釋放代碼:

for(int i=0;i<4;i++)delete x[i];

delete[]x;

運行一試,OK!大功告成!

所以,使用VCL數組的過程是:首先聲明一個二重指針,然後分配所要VCL組件的個數,最後再對每個VCL元件進行分配;在釋放的時侯,要釋放每個VCL元件的資源,最後才回收VCL數組的資源。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved