实验15 模板和异常处理.docVIP

  • 5
  • 0
  • 约3.42千字
  • 约 5页
  • 2018-11-24 发布于河南
  • 举报
实验15 模板和异常处理

实验15 模板和异常处理实验目的和要求理解函数模板与类模板的概念。掌握函数模板的应用。掌握类模板的应用。理解出现异常时的处理方法。实验内容任务1:程序调适下列程序应用一个函数模板,其功能为使用冒泡排序将不同类型的数组内容由小到大排列。函数的参数有两个,其中一个为通用类型的数组,另一个为数组的元素个数,类型为整型。程序代码为:#includeiostream.htemplateclass Tvoid sort(T*array,int size){ int I,j; T temp; for(i=0;isize-1;i++) for(j=0,jsize-i-1;j++) if(array[j]array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; }}测试用的main函数如下:void main(){ int intarray[7]={50,12,9,34,7,8,5}; int i; sort(intarray,7); for(i=0,i7;i++) coutintarray[i]’ ‘;coutendl;double doublearray[7]={22.50,12.34,31.9,3.4,78.7,8.5,9.5};sort(doublearray,7);for(i=0,i7;i++) coutdoublearray[i]’ ‘;coutendl;char chararray[7]={‘t’,’p’,’a’,’h’,’e’,’i’,’h’};sort(chararray,7);for(i=0,i7;i++) coutchararray[i]’ ‘;coutendl;}任务2:程序设计参照任务1,定义一个函数模版,能分别完成对int与int、double与double,int与char型数据的加法。任务3:程序调试程序由两个文件function_template.h、test.cpp构成,请建立文件,并调试程序,修改程序中的错误,回答给出的问题。//文件1 function_template.h#ifndef FUNCTION_TEMPLATE#define FUNCTION_TEMPLATE//函数模版声明templateclass TT sum(T*array,int size){ T total=0; for(int i=0;isize;i++) total+=array[i]; return total;}//模版函数重载templateclass TT sum(T*array1,T*array2,int size){ T total=0; for(int i=0;isize;i++) total+=array1[i]+array2[i]; return total;}templateclass TT max(T x,T y){ return (xy)?x:y;}templateclass TT func(){ T m; return m;}#endif//文件2 test.cpp#include”function_tenmplate.h”#includeiostreamusing namespace std;void main(){ int i; char c; float f; coutmax(i,i)endl; coutmax(c,i)endl; coutmax(c,c)endl; coutmax(f,f)endl; int k=funcint(); static int intarr1[]={1,2,3,4,5,6,7,8,9,10}; static int intarr2[]={2,4,6,8,10,12,14,16}; static double douarr[]={1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.0}; int itotall=sum(intarr1,intarr2,8); coutitotallendl; coutitotallendl; coutdtotalendl;}指出错误语句,并解释原因。函数模版声明与函数模版定义为什么必须一起放在头文件中?指出文件中函数模版的定义及模版函数的重载。任务4:程序设计参照任务1,定义一个数组的函数模版,能够完成对int、double、char型的数组从小到大排序。任务5:程序调试设有表达式:f(a,b,c)=√a+b/c,计算表达式的值,要求能排除除数为0及根号小于0的异常。在求f(a,b,c)表达式时可能会遇到两种异常:除数为0和负数开根号,因此需要设立两个处理这些异常的类YC1、YC2,分别在c为0及

文档评论(0)

1亿VIP精品文档

相关文档