Click to See Complete Forum and Search --> : help with a snippet


yamokosk
July 9th, 2004, 09:07 AM
Alright, i have starred at this for sometime, and while i could try every combination of const modifier, I would rather get an explanation why this won't go. I still get hung up on const stuff...


Matrix& Matrix::operator = (const Matrix& m) {
if (*this == m) {
for (int r = 0; r < rows(); r++) {
for (int c = 0; c < cols(); c++) {
(*this)(r,c) = m(r,c);
}
}
return *this;
} else {
throw std::invalid_argument("Error! Matricies must be equal for assignment.");
}
}


I get the following error on compile:


error C2662: 'cols' : cannot convert 'this' pointer from 'const class Matrix' to 'class Matrix &'
Conversion loses qualifiers
error C2662: 'rows' : cannot convert 'this' pointer from 'const class Matrix' to 'class Matrix &'
Conversion loses qualifiers


Thanks in advance!

Paul McKenzie
July 9th, 2004, 11:22 AM
The error refers to cols() and rows(), but you didn't post what these are. I get no errors with the following code:

class Matrix
{
public:
int nRows;
int nCols;
int rows() const { return nRows; }
int cols() const { return nCols; }

Matrix& operator = (const Matrix& m);
};

Matrix& Matrix::operator = (const Matrix& m)
{
int r = rows();
return *this;
}

Regards,

Paul McKenzie

yamokosk
July 9th, 2004, 12:15 PM
I apologize for the incompleteness of my problem, but I thought it had to do with something i did wrong in that function. Here were the original definitions for that class (exactly as you had guessed):

in header file:

public:
int rows() {return m_nRows;};
int cols() {return m_nCols;};

private:
int m_nRows, m_nCols;


So now i have modifed rows() and cols() to match yours and everything works perfectly. So correct me if I am wrong, but placing the const in rows() and cols() function makes what rows() and cols() pass back const?

Thanks for the assisstance!