我碰到下面的代码来:C++引用和返回值
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 operator()(const int n)'你实际上没有看到'double operator()(const int n)cont'吗? – NathanOliver
简而言之:第一个支持写作;如果对象是const,则第二个可用。 –
[C++中指针变量和引用变量之间的区别是什么?]可能的重复(http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-和-a-reference-variable-in) – piyushj