由static关键字修饰的类成员(数据成员和成员函数)叫做静态成员。静态成员不是对象的一部分,而是类的一部分,这是静态成员和普通成员之间最本质的区别。。

代码清单6.1
  1. #include <iostream>
  2. #include <string.h>
  3. #include <unistd.h>
  4. using namespace std;
  5. class Person
  6. {
  7. private:
  8. static int cnt;
  9. char *name;
  10. int age;
  11. public:
  12. Person()
  13. {
  14. cnt++;
  15. }
  16. static int getCount(void)
  17. {
  18. return cnt;
  19. }
  20. void setName(char *n)
  21. {
  22. name = n;
  23. }
  24. int setAge(int a)
  25. {
  26. age = a;
  27. }
  28. };
  29. int Person::cnt = 0;
  30. int main(int argc, char **argv)
  31. {
  32. Person *p_Person = new Person[10];
  33. cout << "person number = " << Person::getCount() << endl;
  34. return 0;
  35. }

运行结果为

10