Recently in writing games, take the map class template as an example of how to simulate a multidimensional array bar!
Copy Code code as follows:
Template <typename t_cell_style>
Class CMap
{
Public
CMap (in UINT row_num, UINT col_num,
In T_cell_style Cell_style = static_cast<t_cell_style> (0));
Subscript operator Overload
TypeName Vector<t_cell_style>::iterator operator[] (in UINT x);
Public
Const UINT M_row_num; Number of grid rows in a map
Const UINT M_col_num; Number of grid columns in a map
Private
Vector<t_cell_style> _m_map_data; Storing map data
}; /* Class CMAP * *
we know that the subscript operator overload cannot be written in the following form:
T_cell_style operator[][] (in UINT x, in UINT y);
Although it is not possible to implement a pair of subscript operator overloads directly, we can simulate them indirectly.
The idea is this, first through the single subscript operation to return a subscript operation ability of the left value, the left value for subscript operation, two subscript operation expression of the joint implementation of double subscript operation. Let's look at the following examples:
Copy Code code as follows:
Map size
#define _map_row 30
#define _MAP_COL 36
Map Cell Styles
typedef enum {
_cell_ground,
_cell_grass,
_cell_brick,
_cell_steel,
_cell_water
} CellStyle;
Cmap<cellstyle> Mymap (_map_row, _map_col, _cell_ground);
Get map 3rd row column 5th cell style
Vector<t_cell_style>::iterator iter = mymap[3];
CellStyle Acell = iter[5];
We will use the above two subscript operation expressions to be joint, as follows:
CellStyle Acell mymap[3][5];
This gets the double subscript operation and looks like it operates on a two-dimensional array. OK, let's take a look at how to overload.
Copy Code code as follows:
Template <typename t_cell_style>
Inline TypeName Vector<t_cell_style>::iterator
Cmap<t_cell_style>::operator[] (in UINT x)
{
if (m_row_num <= x)
{
Overflow_error e ("overflow-cmap<t_cell_style>::operator[]");
Throw (e);
}
return _m_map_data.begin () + x * m_col_num;
}
See, isn't it simple, the middle process borrows a class type member with the ability of subscript operation.