tiemann@YAHI.STANFORD.EDU (Michael Tiemann) (05/16/89)
I am trying to determine what support there is in C++ for multi-dimensional
arrays within a class. For example, the following class definition attempts to
implement an array of pointers to vectors. Now, I know that I can overload
operator[], but what I would really like to be able to do is overload the
ficticious operator[][]. How can I achieve this functionality? Am I missing
something very obvious?
typedef int Type
class C {
private:
int r, c;
Type** data;
public:
X (int row, int col) {
this->r = row; this->c = col;
this->data = new Type* [row];
for (int i = 0; i < col; i++)
this->data[i] = new Type [col];
}
~X () {
for (int i = 0; i < r; i++)
delete this->data[i];
delete this->data;
}
inline Type* operator[] (int row) {
return this->data[row];
}
inline Type& operator[][] (int row, int col) {
return this->data[row][col];
}
};
You are missing something obvious: you need two kinds of types, a row
type and a matrix type. matrix::operator[] can return a row&, and
row::operator[] can return whatever scalar type interests you. Then,
when you say
mat[row][col] = 5;
this is translated into
row_tmp& = mat[row];
row_tmp[col] = 5;
This is how you cascade operator[], or more generally, any pair of
operators.
Michael