0321537904_ppt73679-0321537904_pptSavitch_ch_11_第1页
0321537904_ppt73679-0321537904_pptSavitch_ch_11_第2页
0321537904_ppt73679-0321537904_pptSavitch_ch_11_第3页
0321537904_ppt73679-0321537904_pptSavitch_ch_11_第4页
0321537904_ppt73679-0321537904_pptSavitch_ch_11_第5页
已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论