鱼C论坛

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

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

[复制链接]
头像被屏蔽
发表于 2011-9-22 02:09:02 | 显示全部楼层 |阅读模式
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-9-22 09:18:22 | 显示全部楼层
本帖最后由 rainymay 于 2011-9-22 09:20 编辑
#include <cstdlib>
#include <iostream>
using namespace std;
const int DEFAULT_SIZE = 10;
enum ErrorType
{
invlidArraySize,memoryAllocationError,indexOutOfRange
};
template <class T>
class Array
{
public:
Array(int size = 10)
{
alist = new T[size];
if(NULL ==alist)
{
cout<<"menoryAllocationError!"<<endl;
exit(-1);
}
cout<<alist<<endl;
length = size;
}
Array<T>(Array<T> &a);
~Array()
{
cout<<"~Array()"<<endl;
cout<<alist<<endl;
delete []alist;
}
int getLength()
{
return length;
}
void set(int index,T value)
{
alist[index] = value;
}
T& get(int index)
{
return alist[index];
}
T &operator[](int index);
private:
int length;
T *alist;
};
template <class T>
Array<T>:: Array(Array<T> &a)
{
this->alist = new T(a.getLength());
if(NULL ==alist)
{
cout<<"menoryAllocationError!"<<endl;
exit(-1);
}
for(int i = 0; i < length; i++)
{
alist = a.alist;
}
this->length = a.getLength();
}
template <class T>
T& Array<T>:: operator[](int index)
{
if(index < 0 || index >= length)
{
cout<<"indexOutOfRange!"<<endl;
exit(-1);
}
return alist[index];
}


int main()
{
Array <int> a(10);
for(int i = 0; i < 10; i++)
{
cout<<&a<<endl;
a.set(i,i);
}
for(int i = 0; i < 10; i++)
{
cout<<&a<<endl;
cout<<a.get(i)<<endl;
}
system("pause");
return 0;
}
修改了下。vs2008无错。。
主要还是构造函数:
alist = new T(size);
当你Array<int> a(10),类构造:int * alist = new int(10)
这样你set时不是访问了不该访问的内存么。
你既然指向数组。应该
alist = new T[size];,类构造:int * alist = new int[10]

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
头像被屏蔽
 楼主| 发表于 2011-9-22 10:40:34 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-2-9 10:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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