static 变量(静态变量)

       在C++的面向对象编程中,static还可以加在类的数据成员或成员函数之前。这样定义的数据成员或成员函数就被类所拥有,而不再属于类的对象

#include <iostream>
using namespace std;
class widget
{
  public:
    widget()
    {
        count++;
    }
    ~widget()
    {
      --count;
    }

    static int num()
    {
      return count;
    }
  private:
    static int count;
};

int widget::count = 0;

int main()
{
  widget x,y;
  cout<<"The Num.is"<<widget::num()<<endl;
  if(widget::num() > 1)
  {
    widget x,y,z;
    cout<<"The Num.is"<<widget::num()<<endl;
  }
  widget z;
  cout<<"The Num.is"<<widget::num()<<endl;
  return 0;
}

       类widget有一个静态成员count和一个静态方法num()。类中的静态成员或方法不属于类的实例,而属于类本身并在所有类的实例间共享。在调用它们时应该用类名加上操作符“::"来引用。

       注意代码中构造函数将静态成员count的值加1,在析构函数中将静态成员函数减1。也就是说静态成员count的值表示类widget实例的个数。

       运行结果:

The Num.is2
The Num.is5
The Num.is3


posted on 2014-04-17 00:15  疯子123  阅读(134)  评论(0编辑  收藏  举报

导航