我有一个代码的基础上,其中用于Matrix类,这两个定义在那里为()操作:

template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)
{
    ......
}


template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const
{
    ......
}

有一件事我明白的是,第二个不返回第二个声明中引用,但什么呢const是什么意思?此外,当我不这样说mat(i,j)该函数被调用?

有帮助吗?

解决方案

哪些功能被称为依赖于实例是否为常量或没有。第一个版本允许你修改实例:

 Matrix<int> matrix;
 matrix(0, 0) = 10;

在常量超负荷允许矩阵的只读访问,如果你有一个const实例(参考):

 void foo(const Matrix<int>& m)
 {
     int i = m(0, 0);
     //...
     //m(1, 2) = 4; //won't compile
 }

在第二个没有由于意图是不允许修改对象(你得到的值的一个拷贝,因此不能修改矩阵实例)返回引用。

下面T被认为是一个简单的数字型这是便宜的(ER)由值返回。如果T也可能是更复杂的用户定义类型,它也将是常见的常量重载返回const引用:

 template <class T>
 class MyContainer
 {
      //..,
      T& operator[](size_t);
      const T& operator[](size_t) const;
 }

其他提示

在const版本将在常量矩阵调用。 上非const矩阵非const版本将被调用。

Matrix<int> M;
int i = M(1,2); // Calls non-const version since M is not const
M(1,2) = 7; // Calls non-const version since M is not const

const Matrix<int> MConst;
int j = MConst(1,2); // Calls const version since MConst is const

MConst(1,2) = 4; // Calls the const version since MConst is const.
                 // Probably shouldn't compile .. but might since return value is 
                 // T not const T.

int get_first( const Matrix<int> & m )
{
   return m(0,0); // Calls the const version as m is const reference
}

int set_first( Matrix<int> & m )
{
  m(0,0) = 1; // Calls the non-const version as m is not const
}

哪些函数被调用取决于对象是否是const。对于const对象const过载被称为:

const Matrix<...> mat;
const Matrix<...>& matRef = mat;
mat( i, j);//const overload is called;
matRef(i, j); //const overloadis called

Matrix<...> mat2;
mat2(i,j);//non-const is called
Matrix<...>& mat2Ref = mat2;
mat2Ref(i,j);//non-const is called
const Matrix<...>& mat2ConstRef = mat2;
mat2ConstRef(i,j);// const is called

这同样适用于指针。如果呼叫是通过一个指针到const的完成,一个const超载被调用。否则,非const过载时被调用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top