C++:通过二维数组中的重载数组下标运算符访问
C++: Access via overloaded array subscript operator in 2D array
对于以下表示矩阵的函数
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
class 是私人的,您将无法在其上调用 operator []
。
使 p 可访问,并且在两个 operator []
实现中,您应该 return 通过引用,而不是通过值。这将允许您修改原始数据,而不是副本的数据。
对于以下表示矩阵的函数
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
class 是私人的,您将无法在其上调用 operator []
。
使 p 可访问,并且在两个 operator []
实现中,您应该 return 通过引用,而不是通过值。这将允许您修改原始数据,而不是副本的数据。