C++对象数组的创建


使用一维指针创建对象数组:

  1. #include <iostream>   
  2. #include <string>   
  3. using namespace std;  
  4.   
  5. int nextStudentID = 1;  
  6. class StudentID  
  7. {  
  8. public:  
  9.     StudentID()  
  10.     {  
  11.         cout << "StudentID()" << endl;  
  12.         value = nextStudentID++;  
  13.         cout << "value:" << value << endl;  
  14.     }  
  15.     ~StudentID()  
  16.     {  
  17.         --nextStudentID;  
  18.         cout << "~StudentID()" << endl;  
  19.     }  
  20. protected:  
  21.     int value;  
  22. };  
  23.   
  24. class Student  
  25. {  
  26. public:  
  27.     Student(string pName = "noName")  
  28.     {  
  29.         cout << "Student()" << endl;  
  30.         name = pName;  
  31.         cout << "name:" << name << endl;  
  32.     }  
  33.     ~Student()  
  34.     {  
  35.         cout << "~Student()" << endl;  
  36.     }  
  37. protected:  
  38.     string name;  
  39.     StudentID id;  
  40. };  
  41.   
  42. int main(int argc, char **argv)  
  43. {  
  44.     int i;  
  45.     cin >> i;  
  46.     Student *p = new Student [i];  
  47.     delete[] p;  
  48.     cout << "nextStudentID:" << nextStudentID << endl;  
  49.     return 0;  
  50. }  

结果:

[cpp]
  1. >>3  
  2. StudentID()  
  3. value:1  
  4. Student()  
  5. name:noName  
  6. StudentID()  
  7. value:2  
  8. Student()  
  9. name:noName  
  10. StudentID()  
  11. value:3  
  12. Student()  
  13. name:noName  
  14. ~Student()  
  15. ~StudentID()  
  16. ~Student()  
  17. ~StudentID()  
  18. ~Student()  
  19. ~StudentID()  
  20. nextStudentID:1  
  • 1
  • 2
  • 下一页

相关内容