Someone asked this question a few days ago in BCB of csdn: "The onclick event of the five buttons changes the name of the five labels." BCB has no control array, so most of the answers at that time were based on rtti. When I was reading C ++ primer yesterday, I suddenly remembered the vector type in the standard library, we can also use this type to implement the control array.
I tried it today and wrote the experiment process here. First, you must include the header file, set the namespace, and declare the variable. In mainform. h:
# Include <vector>
Using namespace STD // Name Space of the standard library
Declare vector <tlabel *> test in public of form1;
Note: Here I tried to initialize the array in the form of vector <tlabel *> test (5), but BCB does not seem to support this form. This problem remains to be solved.
Then, add two buttons and a label (named testlabel) to the main form. In the button1 event, initialize the array.
For (INT I = 0; I <5; I ++)
{
Tlabel * label = new tlabel (this );
Label-> parent = form1;
Label-> Top = 20 * I;
Test. push_back (Label );
}
Test. push_back (testlabel); // test whether the array can contain statically generated controls. The array should contain six member variables.
Write the following code in button2:
For (INT I = 0; I <test. Size (); I ++)
{
Test [I]-> caption = "wolf" + ansistring (I ):
}
In this example, a control array is generated by cyclically assigning values to an array and this array is operated through loops. Here we only show a very rough usage of the vector data type. The STL technology of C ++ can bring more freedom and flexibility to our programming.
The above code is compiled in Win2000 and bcb5 environments.