数组类实现功能:
- 可以定义任意类型
- 动态数组,可以随时修改数组大小
- 可以直接通过"="进行数组复制
- 其它基本操作和普通数组一致
#pragma once
#include<cassert>
#include<iostream>
using namespace std;
template<class T>
class Array
{
public:
Array(int sz=50)
{
assert(sz>=0); //sz大小应该非负,否则终止程序
size = sz;
list = new T[size];
}
Array(const Array<T> &a) //深层复制
{
int i;
size = a.size;
list = new T[size];
for(i=0;i<size;i++)
list[i] = a.list[i];
}
~Array() { delete []list; }
int Getsize() const { return size; }
void resize(int sz) //修改数组的大小
{
int i, n;
assert(sz>=0);
T *newList = new T[sz];
n = size<sz?size:sz;
for(i=0;i<n;i++) //如果数组变小,多余的数字全部截掉
newList[i] = list[i];
for(;i<sz;i++) //如果数组变小,剩下的空间初始化为0
newList[i] = 0;
delete []list;
list = newList;
size = sz;
}
Array<T>& operator = (const Array<T> &oth) //重载"="
{
int i;
if(&oth==this)
return *this;
if(size!=oth.size)
{
delete []list;
list = new T[oth.size];
size = oth.size;
}
for(i=0;i<size;i++)
list[i] = oth.list[i];
return *this;
}
T& operator [] (int k) //重载"[]”,必须返回引用(左值)
{
assert(k>=0 && k<size); //越界检查
return list[k];
}
const T& operator [] (int k) const //重载"[]”常函数
{
assert(k>=0 && k<size);
return list[k];
}
operator T* () { return list; } //别忘了重载指针转换运算符!!
private:
T *list; //用于存放动态分配的数组内存首地址
int size; //数组大小(元素个数)
};
int main(void)
{
int i, n;
scanf("%d", &n);
Array<int> a(n);
for(i=0;i<=n-1;i++)
scanf("%d", &a[i]);
Array<int> b(8);
b = a;
b.resize(8);
printf("%d\n", b.Getsize());
for(i=0;i<b.Getsize();i++)
printf("%d ", b[i]);
puts("");
return 0;
}