下面的程序老是出错!
#include <iostream.h>
template <class T>
class Array
{
int maxsize;//数组允许的最大元素个数
int size; //当前数组实际元素个数
T *arrayPtr;//数组存储空间的头指针
public:
Array(int=10);//构造函数,默认数组大小为10
~Array() { delete []arrayPtr; }//Array的析构函数
T & operator [](int n);//重载下标运算符[ ]
T & operator <<(istream&oa,T &x);//重载插入运算符<<
bool SetElem(T x,int n);//将数据x写入下标为n的数组元素中
bool GetElem(T &,int);//返回下标为n的数组元素值
void invert(); //倒置数组(数组中第一个元素排到最后,第二个元素排到倒数第二…)
void sort(); //任选一种排序算法,对于结构类数组和对象数组,需重载比较运算符
void Print()
{template <class T> Array<T>::Array(int s)
{
maxsize=s>0?s:10;
size=0;
arrayPtr=new T[maxsize];
}
template <class T>
bool Array<T>::SetElem(T x,int n)
{
if (n<0 || n>=maxsize)
{
cout<<"错误:下标"<<n<<"超界,不能写入。\n";
return false;
}
if (n>=size)//写到最后一个元素后
arrayPtr[size]=x,size++;//数组元素个数增1;
else
arrayPtr[n]=x;//改写原有元素
return true;
}
template <class T>
bool Array<T>::GetElem(T& x,int n)
{
if(n<0 || n>=size)
{
cout<<"错误:下标"<<n<<"超界。\n";
return false;
}
x=arrayPtr[n];
return true;
}
template <class T>
T& Array<T>::operator [](int n)
{
//static T x;
if (n<0)
{
cout<<"下标必须大于或等于0!\n";
if (size==0) size=1;
return arrayPtr[0]; //当最小下标处理
}
if (n>=maxsize)
{
cout<<"下标"<<n<<"太大,超界!\n";
if (size<maxsize) size++;
return arrayPtr[size-1];//下标超上界,在数组尾部增加一元素
}
if (n>=size) size=n+1;
return arrayPtr[n];
}
//以上内容可以作为头文件存储,在应用程序中
//只要用"#include"命令把它包含进来即可。
#include <string.h>
class student
{
int id;
char name[12];
public:
void Set(int i,char *nm)
{ id=i;strcpy(name,nm); }
friend ostream& operator <<(ostream& os,student &rp);
};
ostream& operator <<(ostream &os,student &p)
{ //对student对象,重载运算符<<
cout<<p.id<<","<<p.name<<" ";
return os;
}
void main()
{
Array<double> a(8);
int i,k=1;double d;
for (d=20.1,i=-2;i<6;i++)
if (a.SetElem(d,i)) d++;
cout<<"当前数组a的元素为:";a.Print();
d=10.1;i=0;
while (a.SetElem(d,i)) {cout<<d<<" ";d+=0.5;i++;}
cout<<"当前数组a的元素为:";a.Print();
if (a.GetElem(d,3)) cout<<"下标为3的元素是"<<d<<endl;
if (a.GetElem(d,10)) cout<<"下标为10的元素是"<<d<<endl;
Array<int> b;
for (i=0;i<12;i++,k++)
b.SetElem(k,i);
cout<<"当前数组b的元素为:";b.Print();
for (i=0;i<8;i++) a[i]=i+10; //由于重载运算符"[ ]"
cout<<"当前数组a的元素为:";
for (i=0;i<8;i++)
cout<<a[i]<<" "; //由于重载运算符"[ ]"
cout<<endl;
Array<student> s(6);
student st;
char *nm[]={"Wang","Zhang","Huang","Zhou","Yang","Chen","Liu"};
int Id=1401080301;
for (i=0;i<7;i++)
{
st.Set(Id+i,nm[i]);
s[i]=st; //由于重载运算符"[ ]"
}
cout<<"当前数组s的元素为:";
s.Print(); //用到对student对象重载"<<"
}