用静态数据成员和静态函数统计猫的数量——11-01.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <iostream>
  2. // Cat class definition
  3. class Cat {
  4. public:
  5. static int HowManyCats; // Static data member to keep track of the number of Cat objects
  6. // Constructor that takes age as a parameter
  7. Cat(int age) : age(age) {
  8. ++HowManyCats;
  9. }
  10. // Destructor
  11. ~Cat() {
  12. std::cout << "destructing of the cat!" << std::endl;
  13. --HowManyCats;
  14. }
  15. // Static member function to get the number of Cat objects
  16. static int GetHowMany() {
  17. return HowManyCats;
  18. }
  19. private:
  20. int age; // Age of the cat
  21. };
  22. int Cat::HowManyCats = 0; // Initialize static data member
  23. // Function to create an array of 5 Cat objects with ages 1, 2, 3, 4, 5
  24. void creating() {
  25. std::cout << "before the Cat array is created, the number of the cat is:" << Cat::GetHowMany() << std::endl;
  26. Cat* cats[5]; // Array of pointers to Cat objects
  27. // Create 5 Cat objects with ages 1, 2, 3, 4, 5
  28. for (int i = 0; i < 5; ++i) {
  29. cats[i] = new Cat(i + 1);
  30. }
  31. std::cout << "after the Cat array is created, the number of the cat is:" << Cat::GetHowMany() << std::endl;
  32. // Delete the 5 Cat objects to free memory and reduce the count
  33. for (int i = 0; i < 5; ++i) {
  34. delete cats[i];
  35. }
  36. }
  37. int main() {
  38. std::cout << "before the function, the number of the cat is:" << Cat::GetHowMany() << std::endl;
  39. creating();
  40. std::cout << "after the function, the number of the cat is:" << Cat::GetHowMany() << std::endl;
  41. return 0;
  42. }