为什么静态变量没有被修改

0 c++ static

我正在成员函数 getobj() 中创建一个静态变量 'a' 并通过引用返回它并捕获 b 中的引用。我在另一个成员函数 mod() 中修改了相同的静态变量 'a'。当我打印 b 时,我应该期待 '2' 对吗?为什么静态变量“a”没有修改为 2?

#include <iostream>

using namespace std;

class Test {
  
  public:
  int& getobj() {
    static int a = 1;
    return a;
  }

  void mod() {
    static int a = 2;
  }

};

int main(int arc, char* args[]) {

  Test t;
  int &b = t.getobj();
  cout << "printing b first time and its value is expected : " << b << endl;
  t.mod();
  cout << "printing b second time after modifying and its value has not changed : " << b << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

观察到的输出是

printing b first time and its value is expected : 1
printing b second time after modifying and its value has not changed : 1
Run Code Online (Sandbox Code Playgroud)

Mik*_*CAT 5

变量aingetobj()和变量ainmod()在不同的范围内,是不同的东西。

因此,对ain 的修改mod()不会影响ain getobj()

  • @SriramNagaraj 对于类来说它不是静态的,但对于每个方法来说它不是静态的。正如我在评论中所说,如果你想要一个唯一的 *a* 使其成为类变量,请在类定义中添加 `static int a;` 并在方法中删除 `static int` (2认同)