我遇到以下代码:
class MyClass {
// various stuff including ...
double *myarray;
double &operator() (const int n){
return myarray[n];
}
double operator() (const int n) const {
return myarray[n];
}
// various other stuff ...
}
那么“()”的两个重载的实际区别是什么?我的意思是,我知道“第一个返回对double的引用,第二个返回对double的引用”,但这实际上意味着什么?我什么时候使用一个,什么时候使用另一个?第二个(返回双精度)看起来非常安全和直接。第一个以某种方式危险吗?
它们的不同之处在于,第一个允许您修改数组元素,而第二个仅返回值,因此您可以:
使用:double&operator()
MyClass mm;
mm(1) = 12;
但是也:
std::cout << mm(1);
使用:double运算符()
// mm(1) = 12; // this does not compile
std::cout << mm(1); // this is ok
同样,使用时operator[]
(例如使用)时,返回引用更为常见std::vector::operator[]
。
顺便提一句。通常有两个版本的operator()
-一个常量和第二个非常量。const版本将在const对象上调用,而第二个版本将在非const对象上调用。但通常他们的签名是:
double& operator() (const int n);
const double& operator() (const int n) const;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句