Message-Id: <199706302045.NAA23439@bluesky.com> Comments: Authenticated sender is From: "Kevin Baca" Organization: BlueSky Software To: Timothy Robb Date: Mon, 30 Jun 1997 13:55:39 +0000 MIME-Version: 1.0 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Subject: Re: operator[] question CC: djgpp AT delorie DOT com Precedence: bulk > 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