我正在成员函数 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)
变量aingetobj()和变量ainmod()在不同的范围内,是不同的东西。
因此,对ain 的修改mod()不会影响ain getobj()。