MFC's array classes support arrays similar to regular arrays in C + +, and can hold any data type. A regular array of C + + must be defined before use to accommodate all possible elements, while an MFC array class creates objects that can be dynamically increased or reduced as needed, and the initial subscript of the array is 0, and the upper limit can be fixed or increased as the element increases. The address of an array in memory is still continuously allocated.
MFC defines the array template class CArray and defines Cbytearray,cwordarray,cuintarray,cdwordarray,cstringarray,cobarray,cptrarray for a variety of commonly used variable types. Please refer to the table below:
Array class |
Variable type |
Range of variable values |
Header file |
CArray |
To set various types through the parameter types of the template class |
|
Afxtempl.h |
CByteArray |
8-bit unsigned integer byte type |
0-255 |
Afxcoll.h |
CWordArray |
16-bit unsigned integer word type |
0-65535 |
Afxcoll.h |
CDWordArray |
32-bit unsigned integer DWORD type |
0-4294967295 |
Afxcoll.h |
CUIntArray |
32-bit unsigned integer UINT type |
0-4294967295 |
Afxcoll.h |
CStringArray |
CString string String |
|
Afxcoll.h |
CObArray |
CObject class and its derived classes |
|
Afxcoll.h |
CPtrArray |
void* Type pointer |
|
Afxcoll.h |
MFC array classes Use the same method, and the following example demonstrates how to use the array class, respectively, in CArray and CUIntArray.
Using CArray
Open VC + + 6.0 to create a project array based on the dialog box. Add a statement to the Carraydlg class declaration file (ArrayDlg.h):
#include <afxtempl.h>
Keep in mind: Use CArray must include header file afxtempl.h.
Open the main dialog resource Idd_array_dialog, add a button Idc_array_cpoint, the caption is Carray_cpoint, double-click the button, and add the following code to the Onarraycpoint () function:void CArrayDlg::OnArrayCpoint()
{
CArray <CPoint,CPoint&> m_Array;
m_Array.SetSize(10,10);
CPoint pt1(10,10);
m_Array.Add(pt1);
CPoint pt2(10,50);
m_Array.Add(pt2);
CPoint pt3(10,100);
m_Array.Add(pt3);
int size=m_Array.GetSize();
CClientDC dc(this);
dc.MoveTo(0,0);
CPoint pt;
for(int i=0;i<size;i++)
{
pt=m_Array.GetAt(i);
dc.LineTo(pt);
}
}