因爲,C++ BUILDER是編譯型語言,而非解釋型語言,所以它沒有Visual Foxpro那種宏代換。
事實上,這個問題的提出早在去年夏天就出現過,我當時最笨的辦法就是用枚舉的方法一一列舉,去年11月看了一下STL覺得用MAP容器完全可以解決問題,舉一個簡單的例子來說種這個問題,比如說在TFORM1上我們有20個Edit, 我們假定他們的名稱分別是Edit1到Edit20(當然也可以將其命名爲更有意義的名稱),現在要求通過這些Edit控件的名稱來訪問他們。
解決方案:如果我們事先將這些Edit控件的名稱及指向這些控件的指針存儲起來,然後通過他們的名稱來查找,那麼問題就很容易解決了,如果你看過STL,你很自然就會想到用STL中的MAP容器來解決會比較方便。以下給出代碼:
.h File
#include <map>
class TForm1:public TForm
{
private:
TEdit* __fastcall AccessControlByName(char *ControlName);
public:
protected:
__published:
TEdit *Edit1;
......;
TEdit *Edit20;
......
}
//To define a global map,which will be used to store all edit's pointer and name
typedef std::map<TEdit*,String>EditProp;
EditProp AllEdit;
.cpp File
void __fastcall TForm1::FormCreate(TObject *Sender)
//First of all,storing all edit's pointer and name
for(int i=0;i<ComponentCount;i++)
{
TEdit *pEdit=dynamic_cast<TEdit*>(Components[i]);
if(pEdit)
{
AllEdit.insert(EditProp::value_type(pEdit,pEdit->Name));
}
}
}
void __fastcall TForm1::OnDestroy(TObject *Sender)//Clear all elements in map
{
AllEdit.Clear();
}
TEdit* __fastcall TForm1::AccessControlByName(char *ControlName)
{
EditProp::iterator theIterator=AllEdit.find(String(ControlName));
if(theIterator!=AllEdit.end())
{
return (*theIterator).second;/return TEdit*
}
else
{
//TODO:Add your code here.....
return NULL;
}
}
//聲明以上只是我程序的大致框架,已完全表達出我的思路,如果要加入到你的程序中需要作出調整。