How to access the object through the object name in C ++ Builder? The answer is to use the MAP container.

zhaozj2021-02-16  44

Because C Builder is a compilation language, not the interpreted language, so it doesn't have Visual FoxPro that macro change. In fact, this problem has appeared last summer, I was the most stupid method to use the enumeration method one by one, I saw STL, I saw the STL, I feel that I can solve the problem with the MAP container, and give a simple The example is this problem. For example, in TForm1 we have 20 Edit, we assume that their names are edit1 to edit20 (of course, they can also name their more meaningful names), and now require these EDIT controls Name to access them. Solution: If we store the names of these EDIT controls and points to these controls, we will find it through their name, then the problem is easy to solve, if you have seen STL, you will naturally think of it. The MAP container in the STL is relatively convenient. The following is given:

.h file # include Class TForm1: PUBLIC TFORM {Private: Tedit * __fastcall accessControlbyName (char * controlname); public: protected: __ public: tedit * edit1; ...; tedit * edit20; ... ...} // to define a global map, which will be used to store all edit's pointer and nametypedef std :: map EditProp; EditProp AllEdit; .cpp Filevoid __fastcall TForm1 :: FormCreate (TObject * Sender )

// first of all, storing all edit's pointer and name for (int i = 0; i (Components [i]); if (PEDIT) {alleDit.insert (Editprop :: value_type);}}} void __fastcall tform1 :: overdestroy (TOBJECT * Sender) // Clear All Elements in map {alledit.clear ();} TEDIT * __FASTCALL TFORM1 :: AccessControlbyName (Char * ControlName) {editprop :: iterator theiterator = alleDit.find (Strin)); if (theiterator! = AlleDit.end ()) {return (* theiterator). Second; / return TEDIT *

} Else {// Todo: add your code here ..... Return null;}} // Declaration is just the rough framework of my program, fully expressing my idea, if you want to join your program needs to make Adjustment.

转载请注明原文地址:https://www.9cbs.com/read-27101.html

New Post(0)