一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C++ static 静态变量的使用方法

时间:2011-05-12 编辑:简简单单 来源:一聚教程网

在类中,静态成员可以实现多个对象之间的数据共享,并且使用静态数据成员还不会破坏隐藏的原则,即保证了安全性。因此,静态成员是类的所有对象中共享的成员,而不是某个对象的成员。

  使用静态数据成员可以节省内存,因为它是所有对象所公有的,因此,对多个对象来说,静态数据成员只存储一处,供所有对象共用。静态数据成员的值对每个对象都是一样,但它的值是可以更新的。只要对静态数据成员的值更新一次,保证所有对象存取更新后的相同的值,这样可以提高时间效率。

  静态数据成员的使用方法和注意事项如下:

  1、静态数据成员在定义或说明时前面加关键字static。

  2、静态成员初始化与一般数据成员初始化不同。静态数据成员初始化的格式如下:

    <数据类型><类名>::<静态数据成员名>=<值>

 

#include
#include
using std::cout;
using std::endl;

long next();

int main() {
  for(int i = 0 ; i < 30 ; i++) {
    cout << std::setw(12) << next ();
  }
  cout << endl;
  return 0;
}

long next () {
  static long last = 0;
  last = last + 1;  
  return last;
}

来看一个利用静态变量做一个统计平均值代码

#include
using namespace std;
 
int f(int i);
 
int main()
{
  int num;
 
  do {
    cout << "Enter numbers (-1 to quit): ";
    cin >> num;
    if(num != -1)
      cout << "average is: " << f(num) << "n";
   
  } while(num > -1);
 
  return 0;
}
 
int f(int i)
{
  static int sum = 0, count = 0;
 
  sum = sum + i;
 
  count++;
 
  return sum / count;
}

初始化静态成员

#include
using std::cout;
using std::endl;

class Box {
  public:
    Box() {
      cout << "Default constructor called" << endl;
      ++objectCount;
      length = width = .0;
    }

    Box(double lvalue, double wvalue, double hvalue) :
                              length(lvalue), width(wvalue), height(hvalue) {
      cout << "Box constructor called" << endl;
      ++objectCount;
    }

    double volume() const {
      return length * width * height;
    }


    int getObjectCount() const {return objectCount;}

  private:
    static int objectCount;
    double length;
    double width;
    double height;
};
int Box::objectCount = 0;

int main() {
  cout << endl;

  Box firstBox(17.0, 11.0, 5.0);
  cout << "Object count is " << firstBox.getObjectCount() << endl;
  Box boxes[5];
  cout << "Object count is " << firstBox.getObjectCount() << endl;

  cout << "Volume of first box = "
       << firstBox.volume()
       << endl;

  const int count = sizeof boxes/sizeof boxes[0];

  cout <<"The boxes array has " << count << " elements."
       << endl;

  cout <<"Each element occupies " << sizeof boxes[0] << " bytes."
       << endl;

  for(int i = 0 ; i < count ; i++)
    cout << "Volume of boxes[" << i << "] = "
         << boxes[i].volume()
         << endl;

  return 0;
}

结果为

Box constructor called
Object count is 1
Default constructor called
Default constructor called
Default constructor called
Default constructor called
Default constructor called
Object count is 6
Volume of first box = 935
The boxes array has 5 elements.
Each element occupies 24 bytes.
Volume of boxes[0] = 1
Volume of boxes[1] = 1
Volume of boxes[2] = 1
Volume of boxes[3] = 1
Volume of boxes[4] = 1

热门栏目