当前位置:天才代写 > tutorial > C语言/C++ 教程 > 在BCB中利用VCL控件数组1

在BCB中利用VCL控件数组1

2017-11-05 08:00 星期日 所属: C语言/C++ 教程 浏览:323

昨晚和网友邬彦华在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数组的资源。

 

    关键字:

天才代写-代写联系方式