【问题标题】:C++: Access via overloaded array subscript operator in 2D arrayC ++:通过二维数组中的重载数组下标运算符访问
【发布时间】:2015-08-26 07:19:12
【问题描述】:

对于以下表示矩阵的函数

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()函数的功能添加到操作符中?

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

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

const p&amp; operator[] (int r) const

和设置为的那个

p&amp; operator[] (int r)

然后确保在任何一种情况下都不会获取值副本。返回引用允许您通过调用函数更改元素值。

【讨论】:

  • 如何“确保在任何一种情况下都不获取值副本”?如果我做对了,则创建的 p 在函数调用后被销毁
  • 这就是为什么你不能重复创建p。它总是需要从矩阵本身中提取出来。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 2015-09-14
    • 1970-01-01
    • 2016-02-06
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多