C++类中的静态成员

  1. #include <iostream>
  2. using namespace std;
  3. class Box
  4. {
  5. public:
  6. static int objectCount;
  7. // 构造函数定义
  8. Box(double l=2.0, double b=2.0, double h=2.0)
  9. {
  10. cout <<"Constructor called." << endl;
  11. length = l;
  12. breadth = b;
  13. height = h;
  14. // 每次创建对象时增加 1
  15. objectCount++;
  16. }
  17. double Volume()
  18. {
  19. return length * breadth * height;
  20. }
  21. private:
  22. double length; // 长度
  23. double breadth; // 宽度
  24. double height; // 高度
  25. };
  26. // 初始化类 Box 的静态成员
  27. int Box::objectCount = 0;
  28. int main(void)
  29. {
  30. Box Box1(3.3, 1.2, 1.5); // 声明 box1
  31. Box Box2(8.5, 6.0, 2.0); // 声明 box2
  32. // 输出对象的总数
  33. cout << "Total objects: " << Box::objectCount << endl;
  34. return 0;
  35. }

C++中的静态成员函数,保证静态成员不被外部更改

  1. #include <stdio.h>
  2. class Test
  3. {
  4. private:
  5. static int cCount;
  6. public:
  7. Test()
  8. {
  9. cCount++;
  10. }
  11. ~Test()
  12. {
  13. --cCount;
  14. }
  15. static int GetCount()
  16. {
  17. return cCount;
  18. }
  19. };
  20. int Test::cCount = 0;
  21. int main()
  22. {
  23. printf("count = %d\n", Test::GetCount());
  24. Test t1;
  25. Test t2;
  26. printf("count = %d\n", t1.GetCount());
  27. printf("count = %d\n", t2.GetCount());
  28. Test* pt = new Test();
  29. printf("count = %d\n", pt->GetCount());
  30. delete pt;
  31. printf("count = %d\n", Test::GetCount());
  32. return 0;
  33. }
  34. 结果
  35. count = 0
  36. count = 2
  37. count = 2
  38. count = 3
  39. count = 2

C++中const修饰静态成员

  1. #include <iostream>
  2. #include <stdio.h>
  3. class Test
  4. {
  5. private:
  6. const static int cCount;
  7. public:
  8. static int GetCount()
  9. {
  10. return cCount;
  11. }
  12. };
  13. const int Test::cCount = 100;
  14. int main()
  15. {
  16. printf("count = %d\n", Test::GetCount());
  17. return 0;
  18. }