为什么我必须对我的函数进行const限定?

时间:2014-06-08 13:04:11

标签: c++ const

以下代码运行正常,但如果我在括号重载函数后省略const限定符,则会出现编译错误:

  

"传递' const矩阵'作为'这个'双重& amp;的论点matrix :: operator()(unsigned int,unsigned int)'丢弃限定符"。

为什么赋值dest(i,j)=src(i,j)会触发编译器错误?这个赋值行不是试图改变常量对象src(它正在改变dest这不是常数)所以为什么paranthesis重载函数必须是const限定的?

#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=0; 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;
}

0 个答案:

没有答案