鱼C论坛

 找回密码
 立即注册
查看: 2688|回复: 2

C++析构出现问题,求解决

[复制链接]
头像被屏蔽
发表于 2011-9-22 02:09:02 | 显示全部楼层 |阅读模式
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2011-9-22 09:18:22 | 显示全部楼层
本帖最后由 rainymay 于 2011-9-22 09:20 编辑
  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4. const int DEFAULT_SIZE = 10;
  5. enum ErrorType
  6. {
  7. invlidArraySize,memoryAllocationError,indexOutOfRange
  8. };
  9. template <class T>
  10. class Array
  11. {
  12. public:
  13. Array(int size = 10)
  14. {
  15. alist = new T[size];
  16. if(NULL ==alist)
  17. {
  18. cout<<"menoryAllocationError!"<<endl;
  19. exit(-1);
  20. }
  21. cout<<alist<<endl;
  22. length = size;
  23. }
  24. Array<T>(Array<T> &a);
  25. ~Array()
  26. {
  27. cout<<"~Array()"<<endl;
  28. cout<<alist<<endl;
  29. delete []alist;
  30. }
  31. int getLength()
  32. {
  33. return length;
  34. }
  35. void set(int index,T value)
  36. {
  37. alist[index] = value;
  38. }
  39. T& get(int index)
  40. {
  41. return alist[index];
  42. }
  43. T &operator[](int index);
  44. private:
  45. int length;
  46. T *alist;
  47. };
  48. template <class T>
  49. Array<T>:: Array(Array<T> &a)
  50. {
  51. this->alist = new T(a.getLength());
  52. if(NULL ==alist)
  53. {
  54. cout<<"menoryAllocationError!"<<endl;
  55. exit(-1);
  56. }
  57. for(int i = 0; i < length; i++)
  58. {
  59. alist = a.alist;
  60. }
  61. this->length = a.getLength();
  62. }
  63. template <class T>
  64. T& Array<T>:: operator[](int index)
  65. {
  66. if(index < 0 || index >= length)
  67. {
  68. cout<<"indexOutOfRange!"<<endl;
  69. exit(-1);
  70. }
  71. return alist[index];
  72. }


  73. int main()
  74. {
  75. Array <int> a(10);
  76. for(int i = 0; i < 10; i++)
  77. {
  78. cout<<&a<<endl;
  79. a.set(i,i);
  80. }
  81. for(int i = 0; i < 10; i++)
  82. {
  83. cout<<&a<<endl;
  84. cout<<a.get(i)<<endl;
  85. }
  86. system("pause");
  87. return 0;
  88. }
复制代码

修改了下。vs2008无错。。
主要还是构造函数:
alist = new T(size);
当你Array<int> a(10),类构造:int * alist = new int(10)
这样你set时不是访问了不该访问的内存么。
你既然指向数组。应该
alist = new T[size];,类构造:int * alist = new int[10]

小甲鱼最新课程 -> https://ilovefishc.com
头像被屏蔽
 楼主| 发表于 2011-9-22 10:40:34 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-10 12:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表