#include <iostream>
using namespace std;
class Test
{
public:
int getStaticVariable() // member function belong to class not instances
{
static int i = 0; // belong to function, so static to class
i++;
return i;
}
private:
int j;
};
int main()
{
Test t1, t2, t3;
cout << t1.getStaticVariable() << endl; // 1
cout << t2.getStaticVariable() << endl; // 2
cout << t1.getStaticVariable() << endl; // 3
cout << t3.getStaticVariable() << endl; // 4
return 0;
}
使用Code::Blocks 12.11,运行结果:
1
2
3
4
t1, t2, t3共享getStaticVariable中i变量,即类拥有成员函数,成员函数中static变量也属于类。