dimanche 8 juin 2014

Why do I HAVE to use consts in my code?


Vote count:

0




The following piece of code runs fine but if I omit the const qualifier after the parenthesis overload function, I get a compile error saying: "passing 'const matrix' as 'this' argument of 'double& matrix::operator()(unsigned int, unsigned int)' discards qualifiers". Also, if I omit the const before the argument type name in the function copy(const matrix&, matrix&) or both this and the one after the parenthesis overload, I get an exception. Could someone please explain to me why these happen?



#include <string>
#include <iostream>

struct matrix
{
protected:
double* mat; //array that stores matrix components
public:
unsigned nrows; unsigned ncols; //ncols = number of columns, nrows = number of rows
matrix(unsigned m, unsigned n): nrows(m), ncols(n)
{
mat = new double[m*n]; //creates an array of size nrows*ncols
for (unsigned k=1; k<=m*n; k++)
mat[k]=0.0;
}
double& operator()(unsigned i, unsigned j) const //parenthesis operator (to access matrix components)
{
if (i>nrows || i<1 || j>ncols || j<1) throw(-1); //index out of bounds
return mat[(i-1)*ncols+(j-1)];
}
~matrix() {delete[] mat;}
};

void copy(const matrix& src, matrix& dest)
{
unsigned m=src.nrows; //sets m to number of rows
unsigned n=src.ncols; //sets n to number of columns
for (unsigned i=1; i<=m; i++)
for (unsigned j=1; j<=n; j++)
dest(i,j)=src(i,j); //copies all the components of src to dest
}

int main()
{
matrix A(2,1);
A(1,1)=11;
A(2,1)=21;
matrix B(2,1);
copy(A,B);
std::cout << B(1,1) << std::endl;
return 0;
}


asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire