www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/30/16:52:51

Message-Id: <199706302045.NAA23439@bluesky.com>
Comments: Authenticated sender is <kbaca AT bluesky DOT skygames DOT com>
From: "Kevin Baca" <kbaca AT skygames DOT com>
Organization: BlueSky Software
To: Timothy Robb <trobb AT neutrino DOT phys DOT laurentian DOT ca>
Date: Mon, 30 Jun 1997 13:55:39 +0000
MIME-Version: 1.0
Subject: Re: operator[] question
CC: djgpp AT delorie DOT com

> 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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019