手机版
你好,游客 登录 注册
背景:
阅读新闻

C++对象数组的创建

[日期:2012-02-19] 来源:Linux社区  作者:sg131971 [字体:大 中 小]

使用二维指针创建动态数组:

[cpp]
  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, j;  
  45.     string temp;  
  46.     cin >> i;  
  47.     Student **p = new Student *[i];  
  48.     for (j = 0; j < i; j++)  
  49.     {  
  50.         cout << "j:" << j << endl;  
  51.         cin >> temp;  
  52.         p[j] = new Student(temp);  
  53.         cout << "nextStudentID:" << nextStudentID << endl;  
  54.     }  
  55.     for (j = i - 1; j >= 0; j--)  
  56.         delete p[j];  
  57. //  delete[] p; // 这句话好像没作用   
  58.     cout << "nextStudentID:" << nextStudentID << endl;  
  59.     return 0;  
  60. }  

结果:

[cpp]
  1. >>3  
  2. j:0  
  3. >>shiguang1  
  4. StudentID()  
  5. value:1  
  6. Student()  
  7. name:shiguang1  
  8. nextStudentID:2  
  9. j:1  
  10. >>shiguang2  
  11. StudentID()  
  12. value:2  
  13. Student()  
  14. name:shiguang2  
  15. nextStudentID:3  
  16. j:2  
  17. >>shiguang3  
  18. StudentID()  
  19. value:3  
  20. Student()  
  21. name:shiguang3  
  22. nextStudentID:4  
  23. ~Student()  
  24. ~StudentID()  
  25. ~Student()  
  26. ~StudentID()  
  27. ~Student()  
  28. ~StudentID()  
  29. nextStudentID:1  

两者的区别:

一维指针在建立指针的时候,申请并创建了三个对象。

二维指针在建立指针的时候,只创建了一个指针数组(即3*4Byte),数组里面的元素用来存放三个对象的地址,各个对象地址在后面由new创建获得。所以对应的delete函数应该是delete p[j];而不是delete[] p。

linux
相关资讯       C++ 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款