C++类成员函数中static变量小测试

来源:互联网 发布:福瑞博德软件开发 编辑:程序博客网 时间:2024/06/05 14:16
#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变量也属于类。

0 0
原创粉丝点击