‘const’ 是什么意思?在operator()中重载吗?
我有一个代码库,其中对于 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)
时会调用哪个函数?
I have a code base, in which for Matrix class, these two definitions are there for ()
operator:
template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)
{
......
}
template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const
{
......
}
One thing I understand is that the second one does not return the reference but what does const
mean in the second declaration? Also which function is called when I do say mat(i,j)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用哪个函数取决于实例是否为 const。第一个版本允许您修改实例:
如果您有 Matrix 的 const 实例(引用),则 const 重载允许只读访问:
第二个版本不返回引用,因为其目的是禁止修改对象(您获取值的副本,因此无法修改矩阵实例)。
这里 T 应该是一个简单的数字类型,按值返回很便宜。如果 T 也可能是更复杂的用户定义类型,则 const 重载返回 const 引用也很常见:
Which function is called depends on whether the instance is const or not. The first version allows you to modify the instance:
The const overload allows read-only access if you have a const instance (reference) of Matrix:
The second one doesn't return a reference since the intention is to disallow modifying the object (you get a copy of the value and therefore can't modify the matrix instance).
Here T is supposed to be a simple numeric type which is cheap(er) to return by value. If T might also be a more complex user-defined type, it would also be common for const overloads to return a const reference:
const 版本将在 const 矩阵上调用。
对于非常量矩阵,将调用非常量版本。
The const version will be called on const Matrices.
On non-const matrices the non-const version will be called.
调用哪个函数取决于对象是否为const。对于
const
对象,调用const
重载:这同样适用于指针。如果调用是通过指向 const 的指针完成的,则会调用 const 重载。否则调用非常量重载。
Which function is called depends on whether the object is
const
. Forconst
objectsconst
overload is called:The same applies to pointers. If the call is done via a pointer-to-const, a const overload is called. Otherwise a non-const overload is called.