- 16
- 0
- 约2.8千字
- 约 5页
- 2018-03-08 发布于河南
- 举报
算法操作作业(第0章 I 模板函数)
贺州学院
《算法设计与分析》上机操作作业
实验名称:函数模板与类模板
实验章节:C++面向对象设计与分析中关于函数模板与类模板的章节
提交形式: 所有作业的原程序和可执行程序(即cpp文件和exe文件)
纸质实验报告(格式和内容请参阅末页)
任课教师: 张波(QQ:404328955)
任课班级:计算机科学与工程系,08计算机软件班
任课时间:2011-2012学年第一学期。
实验内容:
1. 试运行以下程序, 理解函数模板的使用和声明。
#include iostream.h
template class T
T max(T x,T y)
{ return (xy) ? x:y; }
vmain()
{ int i1= 10, i2=56;
float f1=12.5, f2=24.5;
double d1=50.344, d2=4656.346;
char c1=k ‘,c2=n’;
coutThe max of i1,i2 is: max(i1,i2)endl;
coutThe max of f1,f2 is: max(f1,f2)endl;
coutThe max of d1,d2 is: max(d1,d2)endl;
coutThe max of c1,c2 is: max(c1,c2)endl;
return 0;
}#include iostream.h
template class AT
AT sum(AT *array,int size=0)
{
AT total=0;
for(int i=0;isize;i++)
total+=array[i];
return total;
}
int int_array[]={1,2,3,4,5,6};
double d_array[]={1.1,2.2,3.3,4.4,5.5};
main()
{
int itotal=sum(int_array,6);
double dtotal=sum(d_array,5);
coutitotal= itotalendl;
coutdtotal= dtotalendl;
}#includeiostream.h
templatetypename type1,typename type2
void myfunc(type1 x,type2 y)
{
coutxyendl;
}
main()
{
myfunc(10,hao);
myfunc(0.123,10L);
return 0;
}
#includeiostream.h
const int size=10;
class stack {
public:
void init(){ tos=0; }
private:
int tos;
};template class Type //每个成员函数都要加上模板声明
void stackType::push(Type ob) //stackType
{ if (tos==size)
{ coutstack is full; return ; }
stck[tos]=ob;
tos++;
}
template class Type
Type stack Type::pop(){
if (tos==0)
{
coutstack is empty;
return 0;
}
tos--;
return stck[tos];
}
void main()
{ //定义字符堆栈
stack char s1,s2; //创建两个模板参数为char型的对象
int i;
s1.init(); s2.init();
s1.push(’a’); s2.push(’x’);
s1.push(’b’); s2.push(’y’);
s1.push(’c’); s2.push(’z’);
for(i=0;i3;i++) coutpop s1: s1.pop()endl;
for(i=0;i3;i++) coutpop s2: s2.pop()endl;
//定义整型堆栈
stack int is1,is2; //创建两个模板参数为int型的对象
is1.init(); is
您可能关注的文档
最近下载
- 2025年普通高等学校招生全国统一考试(黑吉辽蒙)化学含答案.docx VIP
- 蒂森电梯MC2电气原理图纸标注.pdf
- XCT80L6_1汽车起重机技术规格书.pdf VIP
- 索尼SW7600GR中文说明书.pdf
- 2026年时事政治测试题库100道附参考答案(完整版).docx VIP
- 儿科抢救药品临床应用与管理.pptx VIP
- 河北广谋新材料科技有限公司年产600万平方米复合革及隔音布、400万平方米新型复合网项目环境影响报告表.docx VIP
- 部编版语文五年级下册第七单元教材解读大单元集体备课.pptx VIP
- 部编版语文五年级下册第六单元教材解读大单元集体备课.pptx VIP
- 部编版语文五年级下册第五单元教材解读大单元集体备课.pptx VIP
原创力文档

文档评论(0)