因为,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; } } //声明以上只是我程序的大致框架,已完全表达出我的思路,如果要加入到你的程序中需要作出调整。 
|