|
发表于 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]
|
|