Mail Archives: djgpp/1997/06/30/16:52:51
> 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; ...
You can define Matrix::operator[] to return what's called a proxy.
You may call it a RowProxy. Then define RowProxy::operator[] to
return the element of the proper row and column.
example:
class Matrix; // Forward declaration of class Matrix
class RowProxy
{
public:
RowProxy( int row, Matrix& matrix ) _row( row ), _matrix( matrix ) { };
float& operator[]( int i ) { return _matrix._data[ _row ][ i ]; }
private:
int _row;
Matrix& _matrix;
};
class Matrix
{
friend class RowProxy;
public:
RowProxy operator[]( int i ) { return RowProxy( i, *this ); }
private:
float _data[ 4 ][ 4 ];
};
Hope that helps
-Kevin
- Raw text -