Const引用未"更新"

use*_*849 4 c++ const reference

我知道这可能是一个常见的问题,我之前看过类似的问题.我试图围绕"返回const引用"的东西.我似乎陷入了这个看似简单的例子:

#include <iostream>
using namespace std;

class Test {
public:
  int x;

  Test(): x(0) {};

  const int& getX() const {
    return x;
  }
};

int main() {
  Test t;
  int y = t.getX();
  cout << y << endl;
  t.x = 1;
  cout << y << endl; // why not 1?
}
Run Code Online (Sandbox Code Playgroud)

我明白通过const int返回并阻止我使用类似的设置tx y=1,这很好.但是,我希望y在最后一行中为1,但它保持为零,就像getX()返回一个普通的int一样.到底发生了什么?

Bau*_*gen 8

当您通过引用返回时,您可以在整数y中保护结果,该整数与该x点上的成员无关.它只是一个副本t.x,它在初始化点之后的值不会t.x以任何方式依赖于存在的值或状态.

使用引用来观察您想要的行为:

#include <iostream>
using namespace std;

class Test {
public:
  int x;

  Test(): x(0) {};

  const int& getX() const {
    return x;
  }
};

int main() {
  Test t;
  const int &y = t.getX();
  cout << y << endl;
  t.x = 1;
  cout << y << endl; // Will now print 1
}
Run Code Online (Sandbox Code Playgroud)