我有自定义类,其行为类似于矩阵。一切都很好,除了从同一类的其他实例分配一个值。
所以我可以做这样的事情:
Matrix a(5,7);
// du stuff with a
Matrix b(5,7);
Matrix d=a+b;
d=a*5;
d[3][2]=1;
//but I can't do this:
double x=d[3][2];
//at this point I get this error:
main.cpp:604:12: error: passing ‘const Matrix’ as ‘this’ argument of ‘Matrix::Proxy Matrix::operator[](int)’ discards qualifiers
有谁知道,如何解决这个问题?:(
我的矩阵类的实现在这里:
class Matrix {
public:
Matrix(int x, int y);
~Matrix(void);
//overloaded operators
Matrix operator+(const Matrix &matrix) const;
Matrix operator-() const;
Matrix operator-(const Matrix &matrix) const;
Matrix operator*(const double x) const;
Matrix operator*(const Matrix &matrix) const;
friend istream& operator>>(istream &in, Matrix& a);
class Proxy {
Matrix& _a;
int _i;
public:
Proxy(Matrix& a, int i) : _a(a), _i(i) {
}
double& operator[](int j) {
return _a._arrayofarrays[_i][j];
}
};
Proxy operator[](int i) {
return Proxy(*this, i);
}
// copy constructor
Matrix(const Matrix& other) : _arrayofarrays() {
_arrayofarrays = new double*[other.x ];
for (int i = 0; i != other.x; i++)
_arrayofarrays[i] = new double[other.y];
for (int i = 0; i != other.x; i++)
for (int j = 0; j != other.y; j++)
_arrayofarrays[i][j] = other._arrayofarrays[i][j];
x = other.x;
y = other.y;
}
int x, y;
double** _arrayofarrays;
};