C++引用和返回值

bob*_*nto 5 c++ reference

我遇到了以下代码:

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 ...
}
Run Code Online (Sandbox Code Playgroud)

那么"()"这两个重载的实际区别是什么?我的意思是,我知道"第一个返回引用一个double,第二个返回一个double",但这实际意味着什么呢?我什么时候使用那个?我何时会使用另一个?第二个(返回一个)似乎非常安全和直截了当.第一个在某种程度上是危险的吗?

mar*_*inj 6

它们的不同之处在于,第一个允许您修改数组元素,而第二个只返回值,因此您可以:

with:double&operator()

MyClass mm;
mm(1) = 12;
Run Code Online (Sandbox Code Playgroud)

但是也:

std::cout << mm(1);
Run Code Online (Sandbox Code Playgroud)

with:double运算符()

// mm(1) = 12; // this does not compile
std::cout << mm(1); // this is ok
Run Code Online (Sandbox Code Playgroud)

此外,返回引用在使用operator[]时更常见,就像使用时一样std::vector::operator[].

顺便说一句.它的共同点有两个版本operator()- 一个const和第二个非const.const版本将在const对象上调用,而第二个在非const上调用.但通常他们的签名是:

double& operator() (const int n);
const double& operator() (const int n) const;
Run Code Online (Sandbox Code Playgroud)