版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
12Templates1OutlineFunctiontemplatesClasstemplates2KnowledgePointsWritinggenericfunctions
Book:AcceleratedC++,Chapter83ReferenceMaterialsTemplates
Book:C++HowtoProgram(8thedition),Chapter14(15pages)IntroductionManyoftheideasandexamplespresentedinthelastfewlessonshaveillustratedwaysofmakingcode"generalpurpose".SuchasoverloadingfunctionandinheritanceTheideaofatemplateisthatitdefinesoperationsforanunboundedvarietyofrelateddatatypes.ProgrammingusingtypesasparametersIntroductionKindsoftemplateFunctiontemplatesClasstemplatesTheydescribe,insomegeneralway,howtomanipulatedataelements.Theyworkwithanykindofdatathatsupportstherequiredoperations.TothinkAfunctionmax()takestwodataelementsasarguments,andreturnsthelarger.Wmax(inta,intb){
if(a>b)
returna;
else
returnb;}doublemax(doublea,doubleb){
if(a>b)
returna;
else
returnb;}Boxmax(Boxa,Box
b){
if(a>b)
returna;
else
returnb;}Therehastobeabetterway!template<typenameT>Tmax(constT&a,constT&b){
if(a>b)
returna;
else
returnb;}IndicatesatemplateisbeingdefinedTisaformaltemplatetypeparameterFunctiontemplateDescribesafunctionformatthatwheninstantiatedwithparticularsgeneratesafunctiondefinitionWriteonce,usemultipletimesFunctionTemplatesCodesegmentintInput1=PromptAndRead();intInput2=PromptAndRead();cout<<max(Input1,Input2)<<endl;Causesthefollowingfunctiontobegeneratedfromourtemplateintmax(const
int&a,const
int&b){
if(a>b)
returna;
else
returnb;}TemplateFunctionCodesegmentdoubleValue1=4.30;doubleValue2=19.54;cout<<max(Value1,Value2)<<endl;Causesthefollowingfunctiontobegeneratedfromourtemplatedoublemax(const
double&a,const
double&b){
if(a>b)
returna;
else
returnb;}TemplateFunctionOperator>needstobedefinedfortheactualtemplateparametertype.If>isnotdefined,thenacompile-timeerroroccursCodesegmentBoxb1(6,4,7);Boxb2(5,5,8);cout<<max(b1,b2)<<endl;CausesthefollowingfunctiontobegeneratedfromourtemplateBoxmax(constBox&a,constBox&b)
{
if(a>b)
returna;
else
returnb;}TemplateFunctionNotemplatefunction,justacompile-timeerror
Thetemplateparametersmustbeexactmachwheninstantiatingafunctiontemplate.CodesegmentBoxb1(6,4,7);doubled=2.0;cout<<max(b1,d)<<endl;Whatfunctionwillbegeneratedfromourtemplate???TemplateFunctiontemplate<typenameT>TMin(constT&a,constT&b){
if(a<b)
returna;
else
returnb;}intMin(const
int&a,const
int&b){
if(a<b)
returna;
else
returnb;}intmain(){
inta=1,b=2;cout<<Min(a,b)<<endl;
return0;}Forfollowingcodesegment,whatishappened?Compilermatchoverloadingfunctionfirst,andthenmatchtemplatefunctionFunctionTemplatesAdviceboolfind(intval);boolfind(constMatrix&val);template<typenameelemType>boolfind(elemType&val);
Indefinitionoftemplate,theparametersoffunctioncommonlyusereference.ClassTemplatedeclarationtemplate<template_arguments_list>classclass_name{//definitionoftemplate};template<template_arguments_list>return_typeclass_name<template_argument_names_list>::member_function_name(member_function_argument_list){ //body_of_member_function}template<typenameT,intn>classTC{public:TC();
voidAssign(Tsrc);
//...private:TValueArray[n];}ThevaluetemplateparameterThetypetemplateparameterClassTemplatesTC<char,80>A;TC<int,125>B;classTC{public:TC();
voidAssign(charsrc);
//...private:
charValueArray[80];};TCA;classTC{public:TC();
voidAssign(intsrc);
//...private:
intValueArray[125];};TCB;ClassTemplatesExample:generaldatastoringclasstemplate<typenameT>classStore //Classtemplate:implementstoringanytypedata{private: Titem; //tostoredata boolhaveValue; //tomarkwhetherthedataisexistedpublic: Store(void); //defaultconstructor TgetElem(void); //togetthedata voidputElem(Tx); //tostorethedata};//implementationofthedefaultconstructortemplate<typenameT>Store<T>::Store(void):haveValue(0){}template<typenameT>//implementationofthegetElem()TStore<T>::getElem(void){ if(!haveValue) //ifnodatainstore,exittheprogram {cout<<"Noitempresent!"<<endl;exit(1); } returnitem;//returnthestoreddata}template<typenameT>//implementationoftheputElem()voidStore<T>::putElem(Tx){ haveValue=true; item=x;}structStudent{ intid;//学号
floatgpa;//平均分};intmain(){ Studentg={1000,23}; Store<int>s1,s2; Store<Student>s3; s1.putElem(3); s2.putElem(-7); cout<<s1.ge
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年七台河职业学院单招综合素质考试题库及参考答案详解一套
- 2026年白银希望职业技术学院单招职业适应性测试题库及答案详解一套
- 2026年苏州健雄职业技术学院单招职业倾向性考试题库参考答案详解
- 2026年上海政法学院单招综合素质考试题库附答案详解
- 2026年黑龙江省双鸭山市单招职业适应性考试题库及完整答案详解1套
- 2026年江西电力职业技术学院单招职业技能测试题库及完整答案详解1套
- 2026年新疆农业职业技术学院单招职业技能测试题库附答案详解
- 2026年广西培贤国际职业学院单招职业适应性测试题库及参考答案详解一套
- 2026年合肥信息技术职业学院单招综合素质考试题库及答案详解1套
- 2026年宿州学院单招职业适应性考试题库及参考答案详解1套
- 2025变压器类产品型号注册管理
- 学堂在线 雨课堂 学堂云 中国建筑史-元明清与民居 期末考试答案
- 2025年PC/ABS合金项目市场调查研究报告
- 安全文明施工方案完整版
- 2025年北京中化资本有限公司招聘笔试参考题库含答案解析
- 2024-2025学年北京朝阳区九年级初三(上)期末历史试卷(含答案)
- 玻璃绝缘子生产工艺
- 《儒林外史》整本书阅读教学设计案例
- 《邮储业务介绍》课件
- 医疗器械临床评价报告模板
- 污染场地调查评价与修复
评论
0/150
提交评论