64,678
社区成员
发帖
与我相关
我的任务
分享
//myArrayTestMain.cpp
#include"myArray.h"
//#include"MyArray.cpp"
int main()
{
MyArray<int> myArray_1(10);
myArray_1[3] = 100;
cout<<"数组大小:"<<myArray_1.ListSize();
cout<<"\nmyArray_1[3] = "<<myArray_1[3]<<endl;
return 0;
}
//myArray.h
#ifndef MYARRAY_H
#define MYARRAY_H
#include<iostream>
using namespace std;
#ifndef NULL
const int NULL=0;
#endif //NULL
//define the error types
enum ErrorType
{invalidArraySize,memoryAllocationError,indexOutOfRange};
//declare the MyArray template
template<class T>
class MyArray
{
private:
T * alist; //store the head address
int size;
void Error(ErrorType error,int badIndex=0) const;
public:
MyArray(int sz=50);
MyArray(const MyArray<T>& A);
~MyArray(void);
MyArray<T> & operator=(const MyArray<T> & rhs);
T & operator[](int i);
operator T* (void) const;//MyArray类对象名转换成T类型的指针
int ListSize(void) const;
void ReSize(int sz);
};
#endif
///////////////////////////////////////////////////////////////////
//MyArray.cpp
//#include<iostream>
//#include<cstdlib>
#include"myArray.h"
//using namespace std;
//输出错误信息
//error messages
template<class T>
void MyArray<T>::Error(ErrorType error,int badIndex) const
{
#ifndef ERRORMSG
#define ERRORMSG
char *errorMsg[]={"Invalid array size","Memory allocation error","Invalid index:"};
#endif
cout<<errorMsg[error];
if(error==indexOutOfRange)
cout<<badIndex;
cout<<endl;
exit(1);
}
//constructing function
template<class T>
MyArray<T>::MyArray(int sz)
{
if(sz<=0)
Error(invalidArraySize);
size=sz;
alist = new T[size];
if(alist == NULL)
Error(memoryAllocationError);
}
//destructing function
template<class T>
MyArray<T>::~MyArray(void)
{ delete []alist; }
//copy constructing function
template <class T>
MyArray<T>::MyArray(const MyArray<T>& X)
{
int n = X.size;
size = n;
alist = new T[n];
if(alist == NULL)
Error(memoryAllocationError);
T* srcptr = X.alist;
T* destptr = alist;
while(n--)
*destptr++ = *srcptr++;
}
//重载 '=' 操作符
template <class T>
MyArray<T> & MyArray<T>::operator= (const MyArray<T> & rhs)
{
int n = rhs.size;
if(size!=n)
{
delete [] alist;
alist = new T[n];
if(alist == NULL)
Error(memoryAllocationError);
size = n;
}
//开始复制元素
T * destptr = alist;
T * srcptr = rhs.alist;
while(n--)
*destptr++ = *srcptr++;
return * this;
}
//重载下标运算符
template <class T>
T & MyArray<T>::operator[] (int n)
{
if(n < 0||n > size -1)
Error(indexOutOfRange,n);
return alist[n];
}
//重载指针运转换算符
template <class T>
MyArray<T> ::operator T*(void) const
{
return alist;
}
//取当前数组的大小
template <class T>
int MyArray<T>::ListSize(void) const
{
return size;
}
//将数组大小修改为sz
template <class T>
void MyArray<T>::ReSize(int sz)
{
if(sz <= 0)
Error(invalidArraySize);
if(sz == size)
return;
T * newlist = new T[sz];
if(newlist == NULL)
Error(memoryAllocationError);
int n = (sz <=size)?sz : size;
T* srcptr = alist;
T* destptr = newlist;
while(n--)
*destptr++ = *srcptr++;
delete [] alist;
alist = newlist;
size = sz;
}
exprot template<typename T>
void MyArray<T>::ReSize(int sz)
{
....//实现代码
}