PROBLEM: A designer would like to design a class which behaves as a two
dimensional array, including the use of the [][] syntax.
RESPONSE:
One way would be to overload the () operator to access the data, as
follows:
class MyArray {
...
MyArray& operator () (const int row, const int col) { ... }
...
};
Now client code would be able to use the class like that shown below.
This has the advantage of being quite fast.
void function ()
{
MyArray a (100, 100); // create a big one
...
a (12, 12) = 5; // a[12][12] = 5 in C
...
}
RESPONSE: Anders Munch (juul@diku.dk) (edited)
If you insist on using operator[], it could be done using an intermediate
class:
class ArrayRow
{
int* row;
public:
ArrayRow(int* it) { row = it; }
int& operator[](int secondIndex) { return row[secondIndex]; }
};
ArrayRow MyArray::operator[](int firstIndex)
{
return ArrayRow(stat[firstIndex]);
}
This should work: You get all the range checking you want, and you can still
use the usual []-s. The performance penanlty involved in creating the
intermediate 'ArrayRow' object is negliable. - A good compiler might
even optimize it away entirely. The cost is that the code gets distributed
over two classes in a not very intuitive manner. Indeed, the intermediate
class is a trick which would make your code a lot more confusing.
RESPONSE: Luca Cappa (luca.cappa@tiscali.it)
classs MyArray
{
ArrayRow* stat;
public:
ArrayRow MyArray::operator[](int firstIndex);
};