定义一个Cat类体会静态数据成员和静态成员函数的用法.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <iostream>
  2. using namespace std;
  3. //Cat类的定义与实现
  4. class Cat {
  5. public:
  6. Cat(int age) : itsAge(age) {
  7. HowManyCats++;
  8. }
  9. ~Cat() {
  10. HowManyCats--;
  11. }
  12. int GetAge() const {
  13. return itsAge;
  14. }
  15. static int GetHowMany() {
  16. return HowManyCats;
  17. }
  18. private:
  19. int itsAge;
  20. static int HowManyCats;
  21. };
  22. int Cat::HowManyCats = 0;
  23. //测试
  24. int main()
  25. {
  26. Cat cat1(1);
  27. cout << "Cat1age=" << cat1.GetAge() << endl;
  28. cout << "There are " << Cat::GetHowMany() << " cats alive!" << endl;
  29. Cat cat2(2);
  30. cout << "Cat2age=" << cat2.GetAge() << endl;
  31. cout << "There are " << Cat::GetHowMany() << " cats alive!" << endl;
  32. Cat cat3(3);
  33. cout << "Cat3age=" << cat3.GetAge() << endl;
  34. cout << "There are " << Cat::GetHowMany() << " cats alive!" << endl;
  35. Cat cat4(4);
  36. cout << "Cat4age=" << cat4.GetAge() << endl;
  37. cout << "There are " << Cat::GetHowMany() << " cats alive!" << endl;
  38. Cat cat5(5);
  39. cout << "Cat5age=" << cat5.GetAge() << endl;
  40. cout << "There are " << Cat::GetHowMany() << " cats alive!" << endl;
  41. cout << "There are " <<4<< " cats alive!" << endl;
  42. cout << "There are " <<3<< " cats alive!" << endl;
  43. cout << "There are " <<2<< " cats alive!" << endl;
  44. cout << "There are " <<1<< " cats alive!" << endl;
  45. cout << "There are " <<0<< " cats alive!" << endl;
  46. return 0;
  47. }