Mail Archives: djgpp/1997/07/03/00:34:57
Timothy Robb wrote:
>
> I want to create a class which I call matrix and want to access it like
> an array, I know how to implement as single array.
>
> ie
> matrix a(5);
> a[3] = 3;...
>
> But how do I do this
>
> matrix a(5,5);
>
> a[3][0] = 3; ...
The most straightforward (and it's not all that straightforward) way to do
this is to use an intermediate class. For instance (presuming your
convention is that elements are specified row first, column second):
class Matrix
{
public:
class Row
{
private:
Matrix *matrix;
int row;
public:
Row(Matrix *matrix, int row): matrix(matrix), row(row) { }
int operator [](int column);
};
private:
int **data;
int height, width;
protected:
int index(int row, int column);
public:
Matrix(int height, int width); // allocate the space
~Matrix(void); // deallocate the space
// ...
Row operator [](int row);
friend class Row;
};
int Matrix::Row::operator [](int column)
{
return matrix->index(row, column);
}
int Matrix::Row Matrix::operator [](int row)
{
return Matrix::Row(&matrix, row);
}
(I'm sure I've made a technical mistake along the line here, but hopefully
the intention is clear.)
With these definitions, a[2] refers to a Matrix::Row, and thus you can do
further subscription on it, with a[2][3], which refers to row 2, column 3.
--
Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
Alcyone Systems / web / http://www.alcyone.com/max/
San Jose, California, United States / icbm / 37 20 07 N 121 53 38 W
\
"Covenants without the sword / are but words."
/ Camden
- Raw text -