c++ - Can't assign a value to object of my custom class, that shall behave like a matrix -
i have custom class, behaves matrix. works well, except assigning value other instance of same class.
so can stuff like:
matrix a(5,7); // du stuff matrix b(5,7); matrix d=a+b; d=a*5; d[3][2]=1; //but can't this: double x=d[3][2]; //at point error: main.cpp:604:12: error: passing ‘const matrix’ ‘this’ argument of ‘matrix::proxy matrix::operator[](int)’ discards qualifiers
does have idea, how fix this? :(
implementation of matrix class here:
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 ]; (int = 0; != other.x; i++) _arrayofarrays[i] = new double[other.y]; (int = 0; != other.x; i++) (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; };
you have 1 operator[] signature:
proxy operator[](matrix *this, int i) you're trying call this:
proxy operator[](const matrix *, int) the error saying in order convert const matrix * matrix *, const has discarded, bad. should provide const version inside class:
proxy operator[](int) const {...} when inside class, gains first parameter of this, , const after parameter list means first parameter pointer constant object of class, not non-constant one.
Comments
Post a Comment