歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++對象數組的創建

C++對象數組的創建

日期:2017/3/1 10:30:43   编辑:Linux編程

使用一維指針創建對象數組:

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

結果:

[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
Copyright © Linux教程網 All Rights Reserved