读书人

各位哥哥请问点基础有关问题

发布时间: 2012-03-09 16:54:57 作者: rapoo

各位哥哥,请教点基础问题。
刚看到cczlp(不惑)的一段代码如下:

.h
private:
void __fastcall OnTimer(TObject *Sender);

.cpp

__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
TTimer *timer = new TTimer(this);
timer-> Interval = 300;
timer-> OnTimer = OnTimer;
}
void __fastcall TForm1::OnTimer(TObject *Sender)
{
static bool bSet = true;
Memo1-> Text = bSet ? "3 " : " ";
bSet = !bSet;
}

问题

1: TTimer *timer = new TTimer(this);
通常理解为 new 分配空间以后,应该用delete 释放,这个程序不需要么?

2: timer在窗体构造函数中定义,那么在 Form1-> OnDestroy 中为什么不能访问?

3: Memo1-> Text = bSet ? "3 " : " "; 不明白这句中的问号表达式怎么工作的?


[解决办法]
1.程序结束时会自动释放, 好的写法应该有delete, 我是为了方便才没有写;
2.timer是局部变量, 改成全局的或放在TForm1类中就可以了.
.h
private:
TTimer *timer; //添加
void __fastcall OnTimer(TObject *Sender);

__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
timer = new TTimer(this);//这个改了
timer-> Interval = 300;
timer-> OnTimer = OnTimer;
}
3.相当于
if (bSet)
{
Memo1-> Text = "3 ";
}
else
Memo1-> Text = " ";

[解决办法]
timer这个指针到函数结束即被释放
TTimer的实例(new TTimer(this))
在this(Form1)销毁时,也被销毁!

要搞清VCL的Owner和Parent的差别.
[解决办法]
................
Memo1-> Text = bSet ? "3 " : " ";

唯一个三元运算符号
基础才是最重要的
而往往是人们忽略的

读书人网 >C++ Builder

热点推荐