在类中,静态成员可以实现多个对象之间的数据共享,并且使用静态数据成员还不会破坏隐藏的原则,即保证了安全性。因此,静态成员是类的所有对象中共享的成员,而不是某个对象的成员。
使用静态数据成员可以节省内存,因为它是所有对象所公有的,因此,对多个对象来说,静态数据成员只存储一处,供所有对象共用。静态数据成员的值对每个对象都是一样,但它的值是可以更新的。只要对静态数据成员的值更新一次,保证所有对象存取更新后的相同的值,这样可以提高时间效率。
#include <iostream>
#include <iomanip>
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 <iostream>
using std::cout;
using std::endl;
class Box {
public:
Box() {
cout << "Default constructor called" << endl;
++objectCount;
length = width = height = 1.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