




已阅读5页,还剩122页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter11,Friends,OverloadedOperators,andArraysinClasses,Slide11-3,Overview,11.1FriendFunctions11.2OverloadingOperators11.3ArraysandClasses11.4ClassesandDynamicArrays,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,11.1,FriendFunctions,Slide11-5,FriendFunction,ClassoperationsaretypicallyimplementedasmemberfunctionsSomeoperationsarebetterimplementedasordinary(nonmember)functions,Slide11-6,ProgramExample:AnEqualityFunction,TheDayOfYearclassfromChapter6canbeenhancedtoincludeanequalityfunctionAnequalityfunctionteststwoobjectsoftypeDayOfYeartoseeiftheirvaluesrepresentthesamedateTwodatesareequaliftheyrepresentthesamedayandmonth,Slide11-7,DeclarationofTheequalityFunction,WewanttheequalityfunctiontoreturnavalueoftypeboolthatistrueifthedatesarethesameTheequalityfunctionrequiresaparameterforeachofthetwodatestocompareThedeclarationisboolequal(DayOfYeardate1,DayOfYeardate2);NoticethatequalisnotamemberoftheclassDayOfYear,Slide11-8,DefiningFunctionequal,Thefunctionequal,isnotamemberfunctionItmustusepublicaccessorfunctionstoobtainthedayandmonthfromaDayOfYearobjectequalcanbedefinedinthisway:boolequal(DayOfYeardate1,DayOfYeardate2)return(date1.get_month()=date2.get_month(),Theequalfunctioncanbeusedtocomparedatesinthismannerif(equal(today,bach_birthday)cout,TheinsertionoperatorisabinaryoperatorThefirstoperandistheoutputstreamThesecondoperandisthevaluefollowingcoutHellooutthere.n;,Slide11-50,ReplacingFunctionoutput,OverloadingtheoperatorallowsustouseinsteadofMoneysoutputfunctionGiventhedeclaration:Moneyamount(100);amount.output(cout);canbecomecoutamount;,BecauseisabinaryoperatorcoutIhaveamountinmypurse.;seemsasifitcouldbegroupedas(coutIhave)amount)inmypurse.;Toprovidecoutasanargumentforamount,(coutIhave)mustreturncout,Slide11-51,Display11.7,WhatDoesReturn?,Slide11-52,OverloadedDeclaration,Basedonthepreviousexample,shouldreturnitsfirstargument,theoutputstreamThisleadstoadeclarationoftheoverloadedoperatorfortheMoneyclass:classMoneypublic:friendostream,Slide11-53,OverloadedoperatorforinputisverysimilartooverloadingthecouldbedefinedthiswayfortheMoneyclassistream,Slide11-55,Display11.8(1-4),Overloading,Slide11-56,Section11.2Conclusion,CanyouDescribethepurposeofamakingafunctionafriend?Describetheuseofconstantparameters?Identifythereturntypeoftheoverloadedoperators?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,11.3,ArraysandClasses,Slide11-58,ArraysandClasses,ArrayscanusestructuresorclassesastheirbasetypesExample:structWindInfodoublevelocity;chardirection;WindInfodata_point10;,Slide11-59,AccessingMembers,WhenanarraysbasetypeisastructureoraclassUsethedotoperatortoaccessthemembersofanindexedvariableExample:for(i=0;idata_pointi.velocity;,TheMoneyclassofChapter11canbethebasetypeforanarrayWhenanarrayofclassesisdeclaredThedefaultconstructoriscalledtoinitializetheindexedvariablesAnarrayofclassMoneyisdemonstratedin,Slide11-60,Display11.9(1-3),AnArrayofMoney,Slide11-61,ArraysasStructureMembers,AstructurecancontainanarrayasamemberExample:structDatadoubletime10;intdistance;Datamy_best;my_bestcontainsanarrayoftypedouble,Slide11-62,AccessingArrayElements,ToaccessthearrayelementswithinastructureUsethedotoperatortoidentifythearraywithinthestructureUsethestoidentifytheindexedvariabledesiredExample:my_best.timeireferencestheithindexedvariableofthevariabletimeinthestructuremy_best,Slide11-63,ArraysasClassMembers,ClassTemperatureListincludesanarrayThearray,namedlist,containstemperaturesMembervariablesizeisthenumberofitemsstoredclassTemperatureListpublic:TemperatureList();/Memberfunctionsprivate:doublelistMAX_LIST_SIZE;intsize;,TocreateanobjectoftypeTemperatureList:TemperatureListmy_data;Toaddatemperaturetothelist:My_data.add_temperature(77);Acheckismadetoseeifthearrayisfullisoverloadedsooutputofthelistiscoutmy_data;,Slide11-64,Display11.10(1-2),OverviewofTemperatureList,Slide11-65,Section11.3Conclusion,CanyouDeclareanarrayasamemberofaclass?Declareanarrayofobjectsofaclass?Writecodetocallamemberfunctionofanelementinanarrayofobjectsofaclass?Writecodetoaccessanelementofanarrayofintegersthatisamemberofaclass?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,11.4,ClassesandDynamicArrays,Slide11-67,ClassesandDynamicArrays,AdynamicarraycanhaveaclassasitsbasetypeAclasscanhaveamembervariablethatisadynamicarrayInthissectionyouwillseeaclassusingadynamicarrayasamembervariable.,Slide11-68,ProgramExample:AStringVariableClass,WewilldefinetheclassStringVarStringVarobjectswillbestringvariablesStringVarobjectsusedynamicarrayswhosesizeisdeterminedwhentheprogramisrunningTheStringVarclassissimilartothestringclassdiscussedearlier,Slide11-69,TheStringVarConstructors,ThedefaultStringVarconstructorcreatesanobjectwithamaximumstringlengthof100AnotherStringVarconstructortakesanargumentoftypeintwhichdeterminesthemaximumstringlengthoftheobjectAthirdStringVarconstructortakesaC-stringargumentandsetsmaximumlengthtothelengthoftheC-stringcopiestheC-stringintotheobjectsstringvalue,Inadditiontoconstructors,theStringVarinterfaceincludes:Memberfunctionsintlength();voidinput_line(istreamCopyConstructordiscussedlaterDestructordiscussedlater,Slide11-70,TheStringVarInterface,UsingtheStringVarinterfaceofDisplay11.11,wecanwriteaprogramusingtheStringVarclassTheprogramusesfunctionconversationtoCreatetwoStringVarobjects,your_nameandour_nameyour_namecancontainanystringmax_name_sizeorshorterinlengthour_nameisinitializedtoBorgandcanhaveanystringof4orlesscharacters,Slide11-71,Display11.11(3),AStringVarSampleProgram,StringVarusesadynamicarraytostoreitsstringStringVarconstructorscallnewtocreatethedynamicarrayformembervariablevalue0isusedtoterminatethestringThesizeofthearrayisnotdetermineduntilthearrayisdeclaredConstructorargumentsdeterminethesize,Slide11-72,Display11.12(1),Display11.12(2),TheStringVarImplementation,Slide11-73,DynamicVariables,DynamicvariablesdonotgoawayunlessdeleteiscalledEvenifalocalpointervariablegoesawayattheendofafunction,thedynamicvariableitpointedtoremainsunlessdeleteiscalledAuseroftheSringVarclasscouldnotknowthatadynamicarrayisamemberoftheclass,socouldnotbeexpectedtocalldeletewhenfinishedwithaStringVarobject,Slide11-74,Destructors,AdestructorisamemberfunctionthatiscalledautomaticallywhenanobjectoftheclassgoesoutofscopeThedestructorcontainscodetodeletealldynamicvariablescreatedbytheobjectAclasshasonlyonedestructorwithnoargumentsThenameofthedestructorisdistinguishedfromthedefaultconstructorbythetildesymbolExample:StringVar();,Slide11-75,StringVar,ThedestructorintheStringVarclassmustcalldeletetoreturnthememoryofanydynamicvariablestothefreestoreExample:StringVar:StringVar()deletevalue;,Usingpointersascall-by-valueparametersyieldsresultsyoumightnotexpectRememberthatparametersarelocalvariablesNochangetotheparametershouldcauseachangetotheargumentThevalueoftheparameterissettothevalueoftheargument(anaddressisstoredinapointervariable)TheargumentandtheparameterholdthesameaddressIftheparameterisusedtochangethevaluepointedto,thisisthesamevaluepointedtobytheargument!,Slide11-76,Display11.13,PointersasCall-by-ValueParameters,Display11.14,Slide11-77,CopyConstructors,Theproblemwithusingcall-by-valueparameterswithpointervariablesissolvedbythecopyconstructor.AcopyconstructorisaconstructorwithoneparameterofthesametypeastheclassTheparameterisacall-by-referenceparameterTheparameterisusuallyaconstantparameterTheconstructorcreatesacomplete,independentcopyofitsargument,Slide11-78,StringVarCopyConstructor,ThiscodefortheStringVarcopyconstructorCreatesanewdynamicarrayforacopyoftheargumentMakinganewcopy,protectstheoriginalfromchangesStringVar:StringVar(constStringVar,Slide11-79,CallingaCopyConstructor,AcopyconstructorcanbecalledasanyotherconstructorwhendeclaringanobjectThecopyconstructoriscalledautomaticallyWhenaclassobjectisdefinedandinitializedbyanobjectofthesameclassWhenafunctionreturnsavalueoftheclasstypeWhenanargumentoftheclasstypeispluggedinforacall-by-valueparameter,Slide11-80,TheNeedForaCopyConstructor,Thiscode(assumingnocopyconstructor)illustratestheneedforacopyconstructorvoidshow_string(StringVarthe_string)StringVargreeting(Hello);show_string(greeting);coutgreetingendl;Whenfunctionshow_stringiscalled,greetingiscopiedintothe_stringthe_string.valueissetequaltogreeting.value,Slide11-81,greeting.value,the_string.value,Hello,TheNeedForaCopyConstructor(cont.),Sincegreeting.valueandthe_string.valuearepointers,theynowpointtothesamedynamicarray,Slide11-82,Whenshow_stringends,thedestructorforthe_stringexecutes,returningthedynamicarraypointedtobythe_string.valuetothefreestoregreeting.valuenowpointstomemorythathasbeengivenbacktothefreestore!,TheNeedForaCopyConstructor(cont.),Slide11-83,TheNeedForaCopyConstructor(cont.),TwoproblemsnowexistforobjectgreetingAttemptingtooutputgreeting.valueislikelytoproduceanerrorInsomeinstancesallcouldgoOKWhengreetinggoesoutofscope,itsdestructorwillbecalledCallingadestructorforthesamelocationtwiceislikelytoproduceasystemcrashingerror,Slide11-84,CopyConstructorDemonstration,Usingthesameexample,butwithacopyconstructordefinedgreeting.valueandthe_string.valuepointtodifferentlocationsinmemory,Slide11-85,Whenthe_stringgoesoutofscope,thedestructoriscalled,returningthe_string.valuetothefreestoregreeting.valuestillexistsandcanbeaccessedordeletedwithoutproblems,CopyConstructorDemonstration(cont.),Slide11-86,WhenToIncludeaCopyConstructor,Whenaclassdefinitioninvolvespointersanddynamicallyallocatedmemoryusingnew,includeacopyconstructorClassesthatdonotinvolvepointersanddynamicallyallocatedmemorydonotneedcopyconstructors,Slide11-87,TheBigThree,ThebigthreeincludeThecopyconstructorTheassignmentoperatorThedestructorIfyouneedtodefineone,youneedtodefineall,Slide11-88,TheAssignmentOperator,Giventhesedeclarations:StringVarstring(10),string2(20);thestatementstring1=string2;islegalBut,sinceStringVarsmembervalueisapointer,wehavestring1.valueandstring2.valuepointingtothesamememorylocation,Slide11-89,Overloading=,Thesolutionistooverloadtheassignmentoperator=soitworksforStringVaroperator=isoverloadedasamemberfunctionExample:operator=declarationvoidoperator=(constStringVarRight_sideistheargumentfromtherightsideofthe=operator,Slide11-90,Definitionof=,Thedefinitionof=forStringVarcouldbe:voidStringVar:operator=(constStringVar,Slide11-91,=Details,Thisversionof=forStringVarComparesthelengthsofthetwoStringVarsUsesonlyasmanycharactersasfitinthelefthandStringVarobjectMakesanindependentcopyoftherighthandobjectinthelefthandobject,Slide11-92,Problemswith=,Thedefinitionofoperator=hasaproblemUsuallywewantacopyoftherighthandargumentregardlessofitssizeTodothis,weneedtodeletethedynamicarrayinthelefthandargumentandallocateanewarraylargeenoughfortherighthandsidesdynamicarrayThenextslideshowsthis(buggy)attemptatoverloadingtheassignmentoperator,Slide11-93,AnotherAttemptat=,voidStringVar:operator=(constStringVar,Slide11-94,ANewProblemWith=,Thenewdefinitionofoperator=hasaproblemWhathappensifwehappentohavethesameobjectoneachsideoftheassignmentoperator?my_string=my_string;Thisversionofoperator=firstdeletesthedynamicarrayinthelefthandargument.Sincetheobjectsarethesameobject,thereisnolongeranarraytocopyfromtherighthandside!,Slide11-95,ABetter=Operator,voidStringVar:operator=(constStringVar,Slide11-96,Section11.4Conclusion,CanyouExplainwhyanoverloadedassignmentoperatorisnotneededwhentheonlydataconsisto
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 自考专业(人力资源管理)考前冲刺测试卷及参考答案详解(基础题)
- 养老院应急预案范文(20篇)
- 2025年工业互联网平台量子通信技术在智能家居通信领域的应用预研报告
- 2025年文化娱乐产业政策环境与产业发展趋势研究报告
- 2025年社区团购市场用户留存与社区团购平台用户活跃度提升策略研究报告
- 江西省部分学校2025-2026学年高三上学期8月百万大联考化学试题(含答案)
- 广东省汕尾市陆河县河城中学2024-2025学年上学期九年级10月月考英语试题(含答案无听力原文及音频)
- 班主任工作例会上校长重要讲话:新学期班主任请把这“三件事”和“一条线”放在心上
- 应对焦虑的课件教学
- 巡道工安全培训教案课件
- 【9化一模】2025年安徽省合肥市包河区中考一模化学试卷(含答案)
- (新版)中国心理卫生协会心理咨询师考试复习题库(浓缩400题)
- 塑料软包装质量安全管理制度2024.05
- T-CNAS 12-2020 成人经口气管插管机械通气患者口腔护理
- 神经外科危重症患者的观察与护理
- 做最勇敢的自己
- 《中国象棋基础教程》课件
- 保险销售技巧培训课件
- 《支气管动脉栓塞术》课件
- 2025年河北石家庄市高速公路集团限公司面向社会公开招聘收费人员150名高频重点提升(共500题)附带答案详解
- 地面铺装室外施工合同
评论
0/150
提交评论