SavCpp8PowerPointsSavitch_ch_11_第1页
SavCpp8PowerPointsSavitch_ch_11_第2页
SavCpp8PowerPointsSavitch_ch_11_第3页
SavCpp8PowerPointsSavitch_ch_11_第4页
SavCpp8PowerPointsSavitch_ch_11_第5页
已阅读5页,还剩122页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter11,Friends,OverloadedOperators,andArraysinClasses,Overview,11.1FriendFunctions11.2OverloadingOperators11.3ArraysandClasses11.4ClassesandDynamicArrays,Slide11-3,11.1,FriendFunctions,FriendFunction,ClassoperationsaretypicallyimplementedasmemberfunctionsSomeoperationsarebetterimplementedasordinary(nonmember)functions,Slide11-5,ProgramExample:AnEqualityFunction,TheDayOfYearclassfromChapter10canbeenhancedtoincludeanequalityfunctionAnequalityfunctionteststwoobjectsoftypeDayOfYeartoseeiftheirvaluesrepresentthesamedateTwodatesareequaliftheyrepresentthesamedayandmonth,Slide11-6,DeclarationofTheequalityFunction,WewanttheequalityfunctiontoreturnavalueoftypeboolthatistrueifthedatesarethesameTheequalityfunctionrequiresaparameterforeachofthetwodatestocompareThedeclarationisboolequal(DayOfYeardate1,DayOfYeardate2);NoticethatequalisnotamemberoftheclassDayOfYear,Slide11-7,DefiningFunctionequal,Thefunctionequal,isnotamemberfunctionItmustusepublicaccessorfunctionstoobtainthedayandmonthfromaDayOfYearobjectequalcanbedefinedinthisway:boolequal(DayOfYeardate1,DayOfYeardate2)return(date1.get_month()=date2.get_month(),Slide11-8,UsingTheFunctionequal,Theequalfunctioncanbeusedtocomparedatesinthismannerif(equal(today,bach_birthday)cout,TheinsertionoperatorisabinaryoperatorThefirstoperandistheoutputstreamThesecondoperandisthevaluefollowingcoutHellooutthere.n;,Slide11-49,ReplacingFunctionoutput,OverloadingtheoperatorallowsustouseinsteadofMoneysoutputfunctionGiventhedeclaration:Moneyamount(100);amount.output(cout);canbecomecoutamount;,Slide11-50,WhatDoesReturn?,BecauseisabinaryoperatorcoutIhaveamountinmypurse.;seemsasifitcouldbegroupedas(coutIhave)amount)inmypurse.;Toprovidecoutasanargumentforamount,(coutIhave)mustreturncout,Slide11-51,Display11.7,OverloadedDeclaration,Basedonthepreviousexample,shouldreturnitsfirstargument,theoutputstreamThisleadstoadeclarationoftheoverloadedoperatorfortheMoneyclass:classMoneypublic:friendostream,Slide11-52,Overloaded,OverloadingtheoperatorforinputisverysimilartooverloadingthecouldbedefinedthiswayfortheMoneyclassistream,Slide11-55,Display11.8(1-4),Section11.2Conclusion,CanyouDescribethepurposeofamakingafunctionafriend?Describetheuseofconstantparameters?Identifythereturntypeoftheoverloadedoperators?,Slide11-56,11.3,ArraysandClasses,ArraysandClasses,ArrayscanusestructuresorclassesastheirbasetypesExample:structWindInfodoublevelocity;chardirection;WindInfodata_point10;,Slide11-58,AccessingMembers,WhenanarraysbasetypeisastructureoraclassUsethedotoperatortoaccessthemembersofanindexedvariableExample:for(i=0;idata_pointi.velocity;,Slide11-59,AnArrayofMoney,TheMoneyclassofChapter11canbethebasetypeforanarrayWhenanarrayofclassesisdeclaredThedefaultconstructoriscalledtoinitializetheindexedvariablesAnarrayofclassMoneyisdemonstratedin,Slide11-60,Display11.9(1-3),ArraysasStructureMembers,AstructurecancontainanarrayasamemberExample:structDatadoubletime10;intdistance;Datamy_best;my_bestcontainsanarrayoftypedouble,Slide11-61,AccessingArrayElements,ToaccessthearrayelementswithinastructureUsethedotoperatortoidentifythearraywithinthestructureUsethestoidentifytheindexedvariabledesiredExample:my_best.timeireferencestheithindexedvariableofthevariabletimeinthestructuremy_best,Slide11-62,ArraysasClassMembers,ClassTemperatureListincludesanarrayThearray,namedlist,containstemperaturesMembervariablesizeisthenumberofitemsstoredclassTemperatureListpublic:TemperatureList();/Memberfunctionsprivate:doublelistMAX_LIST_SIZE;intsize;,Slide11-63,OverviewofTemperatureList,TocreateanobjectoftypeTemperatureList:TemperatureListmy_data;Toaddatemperaturetothelist:My_data.add_temperature(77);Acheckismadetoseeifthearrayisfullisoverloadedsooutputofthelistiscoutmy_data;,Slide11-64,Display11.10(1-2),Section11.3Conclusion,CanyouDeclareanarrayasamemberofaclass?Declareanarrayofobjectsofaclass?Writecodetocallamemberfunctionofanelementinanarrayofobjectsofaclass?Writecodetoaccessanelementofanarrayofintegersthatisamemberofaclass?,Slide11-65,11.4,ClassesandDynamicArrays,ClassesandDynamicArrays,AdynamicarraycanhaveaclassasitsbasetypeAclasscanhaveamembervariablethatisadynamicarrayInthissectionyouwillseeaclassusingadynamicarrayasamembervariable.,Slide11-67,ProgramExample:AStringVariableClass,WewilldefinetheclassStringVarStringVarobjectswillbestringvariablesStringVarobjectsusedynamicarrayswhosesizeisdeterminedwhentheprogramisrunningTheStringVarclassissimilartothestringclassdiscussedearlier,Slide11-68,TheStringVarConstructors,ThedefaultStringVarconstructorcreatesanobjectwithamaximumstringlengthof100AnotherStringVarconstructortakesanargumentoftypeintwhichdeterminesthemaximumstringlengthoftheobjectAthirdStringVarconstructortakesaC-stringargumentandsetsmaximumlengthtothelengthoftheC-stringcopiestheC-stringintotheobjectsstringvalue,Slide11-69,TheStringVarInterface,Inadditiontoconstructors,theStringVarinterfaceincludes:Memberfunctionsintlength();voidinput_line(istreamCopyConstructordiscussedlaterDestructordiscussedlater,Slide11-70,AStringVarSampleProgram,UsingtheStringVarinterfaceofDisplay11.11,wecanwriteaprogramusingtheStringVarclassTheprogramusesfunctionconversationtoCreatetwoStringVarobjects,your_nameandour_nameyour_namecancontainanystringmax_name_sizeorshorterinlengthour_nameisinitializedtoBorgandcanhaveanystringof4orlesscharacters,Slide11-71,Display11.11(3),TheStringVarImplementation,StringVarusesadynamicarraytostoreitsstringStringVarconstructorscallnewtocreatethedynamicarrayformembervariablevalue0isusedtoterminatethestringThesizeofthearrayisnotdetermineduntilthearrayisdeclaredConstructorargumentsdeterminethesize,Slide11-72,Display11.12(1),Display11.12(2),DynamicVariables,DynamicvariablesdonotgoawayunlessdeleteiscalledEvenifalocalpointervariablegoesawayattheendofafunction,thedynamicvariableitpointedtoremainsunlessdeleteiscalledAuseroftheSringVarclasscouldnotknowthatadynamicarrayisamemberoftheclass,socouldnotbeexpectedtocalldeletewhenfinishedwithaStringVarobject,Slide11-73,Destructors,AdestructorisamemberfunctionthatiscalledautomaticallywhenanobjectoftheclassgoesoutofscopeThedestructorcontainscodetodeletealldynamicvariablescreatedbytheobjectAclasshasonlyonedestructorwithnoargumentsThenameofthedestructorisdistinguishedfromthedefaultconstructorbythetildesymbolExample:StringVar();,Slide11-74,StringVar,ThedestructorintheStringVarclassmustcalldeletetoreturnthememoryofanydynamicvariablestothefreestoreExample:StringVar:StringVar()deletevalue;,Slide11-75,PointersasCall-by-ValueParameters,Usingpointersascall-by-valueparametersyieldsresultsyoumightnotexpectRememberthatparametersarelocalvariablesNochangetotheparametershouldcauseachangetotheargumentThevalueoftheparameterissettothevalueoftheargument(anaddressisstoredinapointervariable)TheargumentandtheparameterholdthesameaddressIftheparameterisusedtochangethevaluepointedto,thisisthesamevaluepointedtobytheargument!,Slide11-76,Display11.13,Display11.14,CopyConstructors,Theproblemwithusingcall-by-valueparameterswithpointervariablesissolvedbythecopyconstructor.AcopyconstructorisaconstructorwithoneparameterofthesametypeastheclassTheparameterisacall-by-referenceparameterTheparameterisusuallyaconstantparameterTheconstructorcreatesacomplete,independentcopyofitsargument,Slide11-77,StringVarCopyConstructor,ThiscodefortheStringVarcopyconstructorCreatesanewdynamicarrayforacopyoftheargumentMakinganewcopy,protectstheoriginalfromchangesStringVar:StringVar(constStringVar,Slide11-78,CallingaCopyConstructor,AcopyconstructorcanbecalledasanyotherconstructorwhendeclaringanobjectThecopyconstructoriscalledautomaticallyWhenaclassobjectisdefinedandinitializedbyanobjectofthesameclassWhenafunctionreturnsavalueoftheclasstypeWhenanargumentoftheclasstypeispluggedinforacall-by-valueparameter,Slide11-79,TheNeedForaCopyConstructor,Thiscode(assumingnocopyconstructor)illustratestheneedforacopyconstructorvoidshow_string(StringVarthe_string)StringVargreeting(Hello);show_string(greeting);coutgreetingendl;Whenfunctionshow_stringiscalled,greetingiscopiedintothe_stringthe_string.valueissetequaltogreeting.value,Slide11-80,TheNeedForaCopyConstructor(cont.),Sincegreeting.valueandthe_string.valuearepointers,theynowpointtothesamedynamicarray,Slide11-81,greeting.value,the_string.value,Hello,TheNeedForaCopyConstructor(cont.),Whenshow_stringends,thedestructorforthe_stringexecutes,returningthedynamicarraypointedtobythe_string.valuetothefreestoregreeting.valuenowpointstomemorythathasbeengivenbacktothefreestore!,Slide11-82,TheNeedForaCopyConstructor(cont.),TwoproblemsnowexistforobjectgreetingAttemptingtooutputgreeting.valueislikelytoproduceanerrorInsomeinstancesallcouldgoOKWhengreetinggoesoutofscope,itsdestructorwillbecalledCallingadestructorforthesamelocationtwiceislikelytoproduceasystemcrashingerror,Slide11-83,CopyConstructorDemonstration,Usingthesameexample,butwithacopyconstructordefinedgreeting.valueandthe_string.valuepointtodifferentlocationsinmemory,Slide11-84,CopyConstructorDemonstration(cont.),Whenthe_stringgoesoutofscope,thedestructoriscalled,returningthe_string.valuetothefreestoregreeting.valuestillexistsandcanbeaccessedordeletedwithoutproblems,Slide11-85,WhenToIncludeaCopyConstructor,Whenaclassdefinitioninvolvespointersanddynamicallyallocatedmemoryusingnew,includeacopyconstructorClassesthatdonotinvolvepointersanddynamicallyallocatedmemorydonotneedcopyconstructors,Slide11-86,TheBigThree,ThebigthreeincludeThecopyconstructorTheassignmentoperatorThedestructorIfyouneedtodefineone,youneedtodefineall,Slide11-87,TheAssignmentOperator,Giventhesedeclarations:StringVarstring(10),string2(20);thestatementstring1=string2;islegalBut,sinceStringVarsmembervalueisapointer,wehavestring1.valueandstring2.valuepointingtothesamememorylocation,Slide11-88,Overloading=,Thesolutionistooverloadtheassignmentoperator=soitworksforStringVaroperator=isoverloadedasamemberfunctionExample:operator=declarationvoidoperator=(constStringVarRight_sideistheargumentfromtherightsideofthe=operator,Slide11-89,Definitionof=,Thedefinitionof=forStringVarcouldbe:voidStringVar:operator=(constStringVar,Slide11-90,=Details,Thisversionof=forStringVarComparesthelengthsofthetwoStringVarsUsesonlyasmanycharactersasfitinthelefthandStringVarobjectMakesanindependentcopyoftherighthandobjectinthelefthandobject,Slide11-91,Problemswith=,Thedefinitionofoperator=hasaproblemUsuallywewantacopyoftherighthandargumentregardlessofitssizeTodothis,weneedtodeletethedynamicarrayinthelefthandargumentandallocateanewarraylargeenoughfortherighthandsidesdynamicarrayThenextslideshowsthis(buggy)attemptatoverloadingtheassignmentoperator,Slide11-92,AnotherAttemptat=,voidStringVar:operator=(constStringVar,Slide11-93,ANewProblemWith=,Thenewdefinitionofoperator=hasaproblemWhathappensifwehappentohavethesameobjectoneachsideoftheassignmentoperator?my_string=my_string;Thisversionofoperator=firstdeletesthedynamicarrayinthelefthandargument.Sincetheobjectsarethesameobject,thereisnolongeranarraytocopyfromtherighthandside!,Slide11-94,ABetter=Operator,voidStringVar:operator=(constStringVar,Slide11-95,Section11.4Conclusion,CanyouExplainwhyanoverloadedassignmentoperatorisnotneededwhentheonlydataconsistofbuilt-intypes?Explainwhatades

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论