在2D数组中通过重载数组下标操作符进行访问

C++: Access via overloaded array subscript operator in 2D array

本文关键字:数组 操作符 下标 访问 2D 重载      更新时间:2023-10-16

对于下面表示矩阵的函数

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]);
        }
};

操作符用于元素访问,但不能用于元素更改。如何将assign()函数的功能添加到算子中?

将第一个访问器重新定义为

const p& operator[] (int r) const

和一个设置为

p& operator[] (int r)

然后确保在这两种情况下都没有取值拷贝。返回一个引用允许您通过调用函数更改元素值。

您的p类是私有的,您将无法在其上调用operator []

使p可访问,并且在两个operator []实现中您应该通过引用返回,而不是通过值返回。这将允许您修改原始数据,而不是副本。