delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/03/00:34:57

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: operator[] question
Date: Mon, 30 Jun 1997 20:59:22 -0700
Organization: Alcyone Systems
Lines: 73
Message-ID: <33B8809A.271D9EA1@alcyone.com>
References: <Pine DOT SGI DOT 3 DOT 91 DOT 970630152536 DOT 6878A-100000 AT neutrino DOT phys DOT laurentian DOT ca>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


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