Error while overloading operators

Hi, I'm programming a class for manipulating real matrices. I'm having some problems when doing a sentence like "c = a+b". The code is:

class Matrix {
public:
Matrix(int n, int m);
Matrix(Matrix* copy);
~Matrix();
Matrix& operator=(Matrix& copy);
Matrix operator+(Matrix& plus);
float GetEntry(int i, int j);
float GetEntry(int i);
int GetHeight();
int GetWidth();
void SetEntry(int i, int j, float x);
void SetEntry(int i, float x);
Matrix Minor(int i, int j);
Matrix Reduce(int i, int j, float x, bool mode);
Matrix TriangularForm();
Matrix TriangularForm(Matrix* left, Matrix* right);
int Rank();

private:
float* Entry;
int Height;
int Width;
};

Matrix& Matrix::operator=(Matrix& copy) {
int n;
int m;
int i;
n = copy.GetHeight();
m = copy.GetWidth();
if(n != Height || m != Width) {
delete[] Entry;
Entry = new float[n * m];
Height = n;
Width = m;
}
for(i = 0; i < n * m; i++){
Entry[i] = copy.GetEntry(i);
}
return *this;
}

Matrix Matrix::operator+(Matrix& plus) {
int i;
Matrix ans = *this;
for(i = 0; i < Height * Width; i++) {
ans.Entry[i] += plus.GetEntry(i);
}
return ans;
}

int main(){
Matrix a(2,3);
Matrix b(2,3);
cout << "hola!" << endl;
a.SetEntry(0,0,1.0);
a.SetEntry(1,0,2.0);
a.SetEntry(0,1,3.0);
a.SetEntry(1,1,4.0);
a.SetEntry(0,2,5.0);
a.SetEntry(1,2,6.0);
b.SetEntry(0,0,3.0);
b.SetEntry(1,0,5.0);
b.SetEntry(0,1,7.3);
b.SetEntry(1,1,4.0);
b.SetEntry(0,2,-3.0);
b.SetEntry(1,2,1.0);
Matrix c(2,3);
c = a + b;
}

(I'm skipping irrelevant definitions, etc.)

I'm getting the following error when compiling:
src/main.cpp: In function ‘int main()’:
src/main.cpp:34: error: no match for ‘operator=’ in ‘c = Matrix::operator+(Matrix&)(((Matrix&)(& b)))’
src/matrix.h:23: note: candidates are: Matrix& Matrix::operator=(Matrix&)

I can't see why it doesn't work. Could you help me? Thank you in advance
make = take a const Matrix&, or just a Matrix. You can't have a non-const reference to a copy returned by a function.
I did what you said, and I got this:

src/matrix.cpp: In member function ‘Matrix& Matrix::operator=(const Matrix&)’:
src/matrix.cpp:39: error: passing ‘const Matrix’ as ‘this’ argument of ‘int Matrix::GetHeight()’ discards qualifiers
src/matrix.cpp:40: error: passing ‘const Matrix’ as ‘this’ argument of ‘int Matrix::GetWidth()’ discards qualifiers
src/matrix.cpp:48: error: passing ‘const Matrix’ as ‘this’ argument of ‘float Matrix::GetEntry(int)’ discards qualifiers


I don't really get how 'const' objects work...
Google "const correctness".

(in short your GetHeight and other methods that don't modify the matrix should be declared as int GetHeight() const;)
Last edited on
Thanks hamsterman!
Topic archived. No new replies allowed.