gpt4 book ai didi

C++:通过二维数组中的重载数组下标运算符访问

转载 作者:行者123 更新时间:2023-11-27 22:56:42 29 4
gpt4 key购买 nike

对于以下表示矩阵的函数

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& 运算符[] (int r) const

和设置为

p& operator[] (int r)

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

关于C++:通过二维数组中的重载数组下标运算符访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32220277/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com