I want to create a class which has a static method that returns a reference to a static variable(which is declared inside the method). What I want is when calling the method to get the reference of the static variable. Then when I modify it outside the class and call the method again to get the same value I previously set.
Here’s what I tried:
#include <iostream>
using namespace std;
class A
{
public:
static int& f()
{
static int i;
return i;
}
};
int main()
{
static int i;
i = A::f();
cout << i << endl;
i = 11;
cout << i << endl;
i = A::f();
cout << i << endl;
return 0;
}
The problem is that the output of this code is:
0
11
0
Press <RETURN> to close this window...
Why doesn’t it return 0, 11, 11 and how can I make it return 0, 11, 11?
Note: I want the static variable to be explicitly declared inside the method and not as member.
Thanks!
To have the local variable
irefer to the same variable inside the function, declare it as a reference:Otherwise, you’re just creating a new variable and using assigning
A::f()to it.