为何选择返回?

ran*_*tic 5 c++ return reference return-type

我正在阅读"SAMS在21天内自学C++",我遇到了一个我似乎无法理解的例子:

#include<iostream>

using namespace std;

class Counter
{
  public:
    Counter() {itsVal=0;}
    const Counter& operator++ ();
    int GetItsVal() {return itsVal;}
  private:
    int itsVal;
};

const Counter& Counter::operator++()
{
  ++itsVal;
  return *this;
}

int main()
{
  Counter i;
  Counter a = ++i;
  cout << "a: " << a.GetItsVal() << " i: " << i.GetItsVal() << endl;
  ++a;
  cout << "a: " << a.GetItsVal() << " i: " << i.GetItsVal() << endl;
}
Run Code Online (Sandbox Code Playgroud)

为什么++运算符的声明中有"&"?我理解这意味着++运算符的返回类型是一个引用,但它似乎不是对i的引用(因为递增a不会增加i).我注意到如果我同时删除"&",代码会返回相同的结果,但可能效率不高.

Mat*_* M. 5

在C++中,当您创建引用时,它是原始对象的代理:

int i = 0;
int& a = i;

++i;
std::cout << i << " " << a << "\n"; // prints '1 1'

++a;
std::cout << i << " " << a << "\n"; // prints '2 2'
Run Code Online (Sandbox Code Playgroud)

现在,在你的情况下:

  • operator++ 返回对当前对象的引用
  • Counter a = ++i;创建一个新对象(no &after Counter)初始化为引用的副本i

如果您想a参考i,您需要更改其声明:

Counter& a = ++i;
       ^
Run Code Online (Sandbox Code Playgroud)

这将无法编译,因为思想的返回值Counter::operator++Counter const&:你需要删除const这里是不地道的operator++,因此:

Counter& Counter::operator++() { ++itsVal; return *this; }
Run Code Online (Sandbox Code Playgroud)