Operator[][] Overload for Two-Dimensional Arrays
The question arises: can the [] operator be overloaded twice to enable notation like function3 for a two-dimensional array?
Answer: Yes, It Is Possible
To achieve this, one can overload the operator[] to return an object that offers another [] operator for accessing the desired element. Here's an example code:
class ArrayOfArrays { public: ArrayOfArrays() { _arrayofarrays = new int*[10]; for(int i = 0; i < 10; ++i) _arrayofarrays[i] = new int[10]; } class Proxy { public: Proxy(int* _array) : _array(_array) { } int operator[](int index) { return _array[index]; } private: int* _array; }; Proxy operator[](int index) { return Proxy(_arrayofarrays[index]); } private: int** _arrayofarrays; };
This allows usage like:
ArrayOfArrays aoa; aoa[3][5];
Note that the above is a simplified example; additional bounds checking and other features would typically be implemented.
The above is the detailed content of Can the [] Operator Be Overloaded Twice for Two-Dimensional Array Access?. For more information, please follow other related articles on the PHP Chinese website!