⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 array.hxx

📁 安全数组
💻 HXX
字号:
#include<iostream>

using namespace std;

enum errortype
{
	invalidarraysize,
	memoryallocationerror,
	indexoutofrange
};//需要分号

char *errormsg[]={"invalid array size","memory allocation error","index out of range"};

template<class T>
class array
{
private:
	T* arr;
	int size;
	void error(errortype)const;
public:
	array(int sz=100);
	array(const array<T> & a);
	~array(void);
	
	array<T> & operator=(const array<T> & a);
        T & operator[](int i);
	
	int arraysize(void)const;
	void resize(int sz);
	
};


template<class T>
void array<T>::error(errortype errorcomm)const
{
	cout<<errormsg[errorcomm];
	exit(0);
}


template<class T>
array<T>::array(int sz)//不能带默认参数
{
	if(sz<1)
		error(invalidarraysize);
	arr=new T[sz];
	if(arr==NULL)
		error(memoryallocationerror);
	size=sz;
}


template<class T>
array<T>::array(const array<T> &a)
{
	arr=new T[a.size];
	if(arr==NULL)
		error(memoryallocationerror);
	//array(sz);构造函数不能直接调用
	
	int i=size=a.size;
	
	while(i--)//while(i--==0)二者等价
	{
	    arr[i]=a.arr[i];
	}
}

template<class T>
array<T>::~array()
{
	delete [] arr;
	size=0;
}
		
template<class T>
array<T> & array<T>::operator=(const array<T> & a)
{
	delete []arr;
	arr=new T[a.size];
	if(arr==NULL)
		error(memoryallocationerror);
	
	int i=size=a.size;
	
	while(i--)
	{
		arr[i]=a.arr[i];
	}
	return *this;
}

template<class T>
T & array<T>::operator[](int i)
{
	if(i<0||i>=size)
		error(indexoutofrange);
	return *(arr+i);
}

template<class T>
int array<T>::arraysize(void)const
{
	return size;
}

template<class T>
void array<T>::resize(int sz)
{
	if(sz<=0) error(invalidarraysize);
	
	if(sz==size) retrun;//void时可以想返回可以只用retrun 而不返回值
	
	T *newarr=new T[sz];
	if(arr==NULL)
		error(memoryallotionerror);
	
	int n=(sz<=size)?sz:size;
	while(n--)
		newarr[n]=arr[n];
	delete [] arr;
	arr=newarr;
	size=sz;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -