Question:
It's easy to overload the []
operator.
But what if I need a two-dimensional array?
How to overload the [][]
operator?
If I write []
with two parameters – swears. If I write [][]
– swears:
error C2092: тип элемента массива "[]" не может быть функцией
this is how I declare:
double& operator [][] (const int i, const int j);
Answer:
You are not the first to be interested in this problem; this question even got into the official list of frequently asked questions on C ++ at one time.
The famous C++ FAQ advises using operator ()
:
Use
operator()
, notoperator[]
.If you have a multidimensional array, the cleanest solution is to use
operator()
rather thanoperator[]
. The reason is thatoperator[]
always takes one parameter, whileoperator()
takes any number of them (in the case of a rectangular matrix, you need two).
Here and here is an explanation of why parentheses are better than two pairs of square brackets.
Brief summary:
- square brackets require the creation of an intermediate object representing a table row, which imposes a restriction on the physical location of data in the main class.
- parentheses are obviously not worse under any circumstances, and sometimes better
- using native C++ syntax is better
- validation of input parameters is easier, which improves code quality