在2D数组中通过重载数组下标操作符进行访问
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
类是私有的,您将无法在其上调用operator []
。
使p可访问,并且在两个operator []
实现中您应该通过引用返回,而不是通过值返回。这将允许您修改原始数据,而不是副本。
相关文章:
- 矩阵上的数组下标操作符
- 使用PoDoFo-lib从PDF操作符中的数组TJ中提取文本
- 涉及数组指针时delete[]操作符的问题
- 在使用c++类的下标操作符传递的数组中使用关系操作符
- 指针、数组和新的操作符
- 使用自增操作符添加数组元素
- 如何重载下标操作符以允许RPG字符数组
- 用指针数组重载输入操作符
- c++为什么不使用星号操作符访问动态数组
- 重载数组下标操作符
- 内存管理:使用new操作符进行数组和动态分配
- 用模板和指针重载数组操作符
- 如何正确解引用没有[]操作符的多维数组
- 在2D数组中通过重载数组下标操作符进行访问
- 重载2D数组操作符并抛出异常
- 动态数组和操作符重载会导致内存崩溃
- c++静态数组和sizeof操作符
- 动态数组释放(赋值操作符与复制构造函数)
- 泛型数组的重载[]和=操作符
- 使用int的c++模板数组操作符[]