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?

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how to "ensure that a value copy is not taken in either case"? if i get it right, p that is created is destroyed after function call
That's why you can't repeatedly create p. It always needs to be one extracted from the matrix itself.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.