gehongxiang
}
void main() {
double a=3.56,b=8.23;
char s1[]=\ cout<<\输出结果:\
cout<<\中较小者:\ cout<<\中较小者:\ }
输出结果:
3.56,8.23中较小者:3.56 Hello,Good中较小者:Good
题4.设计一个数组类模板Array
本题程序如下: #include
T *elems; int size; public:
Array(int s); // 构造函数 ~Array();
T& operator[](int); // 重载下标运算符 void operator=(T); // 重载等号运算符 };
template
size=s;
elems=new T[size]; for(int i=0;i template delete elems; } template gehongxiang T& Array return elems[index]; } template void Array for(int i=0;i void main() { int i,n=10; Array arr1[i]=’a’+i; // 调用重载运算符 arr2[i]=’a’+i; } cout<<\码 字符\ for(i=0;i cout< 题 5. 一个Sample类模板的私有数据成员为T n,在该类模板中设计一个operator==重载运算符函数 ,用于比较各对象的n数据是否相等。 解: 本题程序如下: #include gehongxiang { T n; public: Sample(T i){n=i;} int operator==(Sample &); }; template int Sample if(n==s.n) return 1; else return 0; } void main() { Sample cout<<\与s2的数据成员\相等\不相等\ Sample cout<<\与s4的数据成员\相等\不相等\ } 本程序的运行结果如下: s1与s2的数据成员不相等 s3与S4的数据成员相等 题 6. 对第3章的例3.5进行修改,只设计一个Sample类,其数据和方法均包含在该类中,而且使用类模板的方式实现。 #include T A[Max]; int n; void qsort(int l,int h); // 私有成员,由quicksort()成员调用 public: Sample(){n=0;} void getdata(); // 获取数据 void insertsort(); // 插入排序 void Shellsort(); // 希尔排序 void bubblesort(); // 冒泡排序 void quicksort(); // 快速排序 void selectsort(); // 选择排序 void disp(); gehongxiang }; template void Sample cout<<\元素个数:\ cin>>n; for(int i=0;i cout<<\输入第\个数据:\ cin>>A[i]; } } template void Sample for(i=1;i temp=A[i]; j=i-1; while(temp A[j+1]=A[j]; j--; } A[j+1]=temp; } } template void Sample int i,j,gap; T temp; gap=n/2; while(gap>0) { for(i=gap;i j=i-gap; while(j>=gap) if(A[j]>A[j+gap]) { temp=A[j]; gehongxiang A[j]=A[j+gap]; A[j+gap]=temp; j=j-gap; } else j=0; } gap=gap/2; } } template void Sample for(i=0;i temp=A[j]; A[j]=A[j-1]; A[j-1]=temp; } } template void Sample qsort(0,n-1); } template void Sample int i=l,j=h; T temp; if(l temp=A[l]; do{ while(j>i&&A[j]>=temp) j--; if(i A[i]=A[j]; i++; }