0

For the following function that represents a matrix

class m // matrix
{
    private:

        double **matrix;
        int nrows, ncols;


        class p
        {
            private:
                double *arr;

            public:
                p (double *a)
                    :   arr (a)
                {
                }

                double &operator[] (int c)
                {
                    return arr[c];
                }
        };


    public:

        m (int nrows, int ncols)
        {
            this->matrix = new double *[nrows];
            for (int i = 0; i < nrows; ++i)
            {
                this->matrix[i] = new double [ncols];
            }
            this->nrows = nrows;
            this->ncols = ncols;
        }

        ~m()
        {
            for (int i = 0; i < this->nrows; ++i)
            {
                delete [] this->matrix[i];
            }
            delete this->matrix;
        }

        void assign (int r, int c, double v)
        {
            this->matrix[r][c] = v;
        }


        p operator[] (int r)
        {
            return p (this->matrix[r]);
        }
};

operator works for element access but does not work with element change. How can I add the functionality of assign() function to the operator?

Kudayar Pirimbaev
  • 1,292
  • 2
  • 21
  • 42
  • 1
    Not yet another jagged edge matrix. Use a contiguous block of memory, pretty please. – Bathsheba Aug 26 '15 at 07:21
  • possible duplicate of [Overloading the subscript operator "\[ \]" in the l-value and r-value cases](http://stackoverflow.com/questions/3854419/overloading-the-subscript-operator-in-the-l-value-and-r-value-cases) – Amit Aug 26 '15 at 07:24
  • 1
    How doesn't it work? [This works fine](http://ideone.com/jdvl6G). – molbdnilo Aug 26 '15 at 08:00

2 Answers2

3

Redefine your first accessor as

const p& operator[] (int r) const

and the one for setting as

p& operator[] (int r)

Then ensure that a value copy is not taken in either case. Returning a reference allows you to change the element value via the calling function.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Your p class is private and you won't be able to call operator [] on it.

Make p accessible, and in both operator [] implementations you should return by reference, not by value. This will allow you to modify original data, not the copy's.

berkus
  • 1,552
  • 12
  • 16