C++ 教程 英文版.ppt_第1页
C++ 教程 英文版.ppt_第2页
C++ 教程 英文版.ppt_第3页
C++ 教程 英文版.ppt_第4页
C++ 教程 英文版.ppt_第5页
已阅读5页,还剩80页未读 继续免费阅读

下载本文档

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

文档简介

1 10 Classes ADeeperLook Part2 2 10 1Introduction constobjectsandconstmemberfunctionsPreventmodificationsofobjectsEnforcetheprincipleofleastprivilegeCompositionClasseshavingobjectsofotherclassesasmembersFriendshipEnablesclassdesignertospecifythatcertainnon memberfunctionscanaccesstheclass snon publicmembers 3 10 1Introduction Cont thispointerDynamicmemorymanagementnewanddeleteoperatorsstaticclassmembersProxyclassesHideimplementationdetailsofaclassfromclientsPointer basestringsUsedinClegacycodefromthelasttwodecades 4 10 2const Constant ObjectsandconstMemberFunctions PrincipleofleastprivilegeOneofthemostfundamentalprinciplesofgoodsoftwareengineeringAppliestoobjects tooconstobjectsKeywordconstSpecifiesthatanobjectisnotmodifiableAttemptstomodifytheobjectwillresultincompilationerrors 5 10 2const Constant ObjectsandconstMemberFunctions Cont constmemberfunctionsOnlyconstmemberfunctioncanbecalledforconstobjectsMemberfunctionsdeclaredconstarenotallowedtomodifytheobjectAfunctionisspecifiedasconstbothinitsprototypeandinitsdefinitionconstdeclarationsarenotallowedforconstructorsanddestructors 6 SoftwareEngineeringObservation10 2 Aconstmemberfunctioncanbeoverloadedwithanon constversion Thecompilerchooseswhichoverloadedmemberfunctiontousebasedontheobjectonwhichthefunctionisinvoked Iftheobjectisconst thecompilerusestheconstversion Iftheobjectisnotconst thecompilerusesthenon constversion 7 CommonProgrammingError10 4 Attemptingtodeclareaconstructorordestructorconstisacompilationerror 8 Outline Time h 1of2 constkeywordtoindicatethatmemberfunctioncannotmodifytheobject 9 Outline Time h 2of2 10 Outline Time cpp 1of3 11 Outline Time cpp 2of3 12 Outline Time cpp 3of3 13 Outline fig10 03 cpp 1of2 Cannotinvokenon constmemberfunctionsonaconstobject 14 Outline fig10 03 cpp 2of2 15 10 2const Constant ObjectsandconstMemberFunctions Cont MemberinitializerRequiredforinitializingconstdatamembersDatamembersthatarereferencesCanbeusedforanydatamemberMemberinitializerlistAppearsbetweenaconstructor sparameterlistandtheleftbracethatbeginstheconstructor sbodySeparatedfromtheparameterlistwithacolon Eachmemberinitializerconsistsofthedatamembernamefollowedbyparenthesescontainingthemember sinitialvalueMultiplememberinitializersareseparatedbycommasExecutesbeforethebodyoftheconstructorexecutes 16 Outline Increment h 1of1 constdatamemberthatmustbeinitializedusingamemberinitializer 17 Outline Increment cpp 1of1 Colon marksthestartofamemberinitializerlist Memberinitializerfornon constmembercount Requiredmemberinitializerforconstmemberincrement 18 Outline fig10 06 cpp 1of1 19 Outline Increment h 1of1 MemberfunctiondeclaredconsttopreventerrorsinsituationswhereanIncrementobjectistreatedasaconstobject 20 Outline Increment cpp 1of1 Itisanerrortomodifyaconstdatamember datamemberincrementmustbeinitializedwithamemberinitializer 21 Outline fig10 09 cpp 1of2 22 Outline fig10 09 cpp 2of2 23 10 3Composition ObjectsasMembersofClasses CompositionSometimesreferredtoasahas arelationshipAclasscanhaveobjectsofotherclassesasmembersExampleAlarmClockobjectwithaTimeobjectasamember 24 10 3Composition ObjectsasMembersofClasses Cont InitializingmemberobjectsMemberinitializerspassargumentsfromtheobject sconstructortomember objectconstructorsMemberobjectsareconstructedintheorderinwhichtheyaredeclaredintheclassdefinitionNotintheordertheyarelistedintheconstructor smemberinitializerlistBeforetheenclosingclassobject hostobject isconstructedIfamemberinitializerisnotprovidedThememberobject sdefaultconstructorwillbecalledimplicitly 25 SoftwareEngineeringObservation10 6 Memberobjectsareconstructedintheorderinwhichtheyaredeclaredintheclassdefinition notintheordertheyarelistedintheconstructor smemberinitializerlist andbeforetheirenclosingclassobjects sometimescalledhostobjects areconstructed 26 Outline Date h 1of1 27 Outline Date cpp 1of3 28 Outline Date cpp 2of3 29 Outline Date cpp 3of3 30 Outline Employee h 1of1 ParameterstobepassedviamemberinitializerstotheconstructorforclassDate constobjectsofclassDateasmembers 31 Outline Employee cpp 1of2 MemberinitializersthatpassargumentstoDate simplicitdefaultcopyconstructor 32 Outline Employee cpp 2of2 33 Outline fig10 14 cpp 1of2 Passingobjectstoahostobjectconstructor 34 Outline fig10 14 cpp 2of2 35 10 4friendFunctionsandfriendClasses friendfunctionofaclassDefinedoutsidethatclass sscopeNotamemberfunctionofthatclassYethastherighttoaccessthenon public andpublic membersofthatclassStandalonefunctionsorentireclassesmaybedeclaredtobefriendsofaclassCanenhanceperformanceOftenappropriatewhenamemberfunctioncannotbeusedforcertainoperations 36 10 4friendFunctionsandfriendClasses Cont Todeclareafunctionasafriendofaclass ProvidethefunctionprototypeintheclassdefinitionprecededbykeywordfriendTodeclareaclassasafriendofaclass PlaceadeclarationoftheformfriendclassClassTwo inthedefinitionofclassClassOneAllmemberfunctionsofclassClassTwoarefriendsofclassClassOne 37 10 4friendFunctionsandfriendClasses Cont Friendshipisgranted nottakenForclassBtobeafriendofclassA classAmustexplicitlydeclarethatclassBisitsfriendFriendshiprelationisneithersymmetricnortransitiveIfclassAisafriendofclassB andclassBisafriendofclassC youcannotinferthatclassBisafriendofclassA thatclassCisafriendofclassB orthatclassAisafriendofclassCItispossibletospecifyoverloadedfunctionsasfriendsofaclassEachoverloadedfunctionintendedtobeafriendmustbeexplicitlydeclaredasafriendoftheclass 38 SoftwareEngineeringObservation10 10 SomepeopleintheOOPcommunityfeelthat friendship corruptsinformationhidingandweakensthevalueoftheobject orienteddesignapproach Inthistext weidentifyseveralexamplesoftheresponsibleuseoffriendship 39 Outline fig10 15 cpp 1of2 friendfunctiondeclaration canappearanywhereintheclass 40 Outline fig10 15 cpp 2of2 friendfunctioncanmodifyCount sprivatedata Callingafriendfunction notethatwepasstheCountobjecttothefunction 41 Outline fig10 16 cpp 1of3 42 Outline fig10 16 cpp 2of3 Non friendfunctioncannotaccesstheclass sprivatedata 43 Outline fig10 16 cpp 3of3 ClassesPartII friendClassExample ClassTwoInterfaceclassClassTwo friendclassClassOne public constructorClassTwo x 0 y 0 z 0 nobodyvoidprint const cout x x endl cout y y endl cout z z endl private intx y z datamembersvoidsetX intval x val voidsetY intval y val voidsetZ intval z val ClassOneInterface include classtwo h classClassOne public voidsetX intval c x val voidsetY intval c y val voidsetZ intval c z val voidprint const cout x c x endl cout y c y endl cout z c z endl private ClassTwoc ClassesPartII CIS554 45 friendClassExampletestdriverandoutput includeclassone hvoidmain ClassOnec1 c1 print c1 setX 5 c1 setY 10 c1 setZ 15 c1 print 46 10 5UsingthethisPointer Memberfunctionsknowwhichobject sdatamemberstomanipulateEveryobjecthasaccesstoitsownaddressthroughapointercalledthis aC keyword Anobject sthispointerisnotpartoftheobjectitselfThethispointerispassed bythecompiler asanimplicitargumenttoeachoftheobject snon staticmemberfunctionsObjectsusethethispointerimplicitlyorexplicitlyImplicitlywhenaccessingmembersdirectlyExplicitlywhenusingkeywordthisTypeofthethispointerdependsonthetypeoftheobjectandwhethertheexecutingmemberfunctionisdeclaredconst 47 Outline fig10 17 cpp 1of2 48 Outline fig10 17 cpp 2of2 Implicitlyusingthethispointertoaccessmemberx Explicitlyusingthethispointertoaccessmemberx Usingthedereferencedthispointerandthedotoperator 49 10 5UsingthethisPointer Cont Cascadedmember functioncallsMultiplefunctionsareinvokedinthesamestatementEnabledbymemberfunctionsreturningthedereferencedthispointerExamplet setMinute 30 setSecond 22 Callst setMinute 30 Thencallst setSecond 22 50 Outline Time h 1of2 setfunctionsreturnTime toenablecascading 51 Outline Time h 2of2 52 Outline Time cpp 1of3 Returningdereferencedthispointerenablescascading 53 Outline Time cpp 2of3 54 Outline Time cpp 3of3 55 Outline fig10 20 cpp 1of2 Cascadedfunctioncallsusingthereferencereturnedbyonefunctioncalltoinvokethenext Notethatthesecallsmustappearintheordershown becauseprintStandarddoesnotreturnareferencetot 56 Outline fig10 20 cpp 2of2 57 10 6DynamicMemoryManagementwithOperatorsnewanddelete DynamicmemorymanagementEnablesprogrammerstoallocateanddeallocatememoryforanybuilt inoruser definedtypePerformedbyoperatorsnewanddeleteForexample dynamicallyallocatingmemoryforanarrayinsteadofusingafixed sizearray 58 10 6DynamicMemoryManagementwithOperatorsnewanddelete Cont OperatornewAllocates i e reserves storageofthepropersizeforanobjectatexecutiontimeCallsaconstructortoinitializetheobjectReturnsapointerofthetypespecifiedtotherightofnewCanbeusedtodynamicallyallocateanyfundamentaltype suchasintordouble oranyclasstypeFreestoreSometimescalledtheheapRegionofmemoryassignedtoeachprogramforstoringobjectscreatedatexecutiontime 59 10 6DynamicMemoryManagementwithOperatorsnewanddelete Cont OperatordeleteDestroysadynamicallyallocatedobjectCallsthedestructorfortheobjectDeallocates i e releases memoryfromthefreestoreThememorycanthenbereusedbythesystemtoallocateotherobjects 60 10 6DynamicMemoryManagementwithOperatorsnewanddelete Cont InitializinganobjectallocatedbynewInitializerforanewlycreatedfundamental typevariableExampledouble ptr newdouble 3 14159 Specifyacomma separatedlistofargumentstotheconstructorofanobjectExampleTime timePtr newTime 12 45 0 61 CommonProgrammingError10 8 Notreleasingdynamicallyallocatedmemorywhenitisnolongerneededcancausethesystemtorunoutofmemoryprematurely Thisissometimescalleda memoryleak 62 10 6DynamicMemoryManagementwithOperatorsnewanddelete Cont newoperatorcanbeusedtoallocatearraysdynamicallyDynamicallyallocatea10 elementintegerarray int gradesArray newint 10 also intarraySize 5 non constint myArray newint arraySize delete myArraySizeofadynamicallyallocatedarraySpecifiedusinganyintegralexpressionthatcanbeevaluatedatexecutiontime 63 10 6DynamicMemoryManagementwithOperatorsnewanddelete Cont Deleteadynamicallyallocatedarray delete gradesArray ThisdeallocatesthearraytowhichgradesArraypointsIfthepointerpointstoanarrayofobjectsFirstcallsthedestructorforeveryobjectinthearrayThendeallocatesthememoryIfthestatementdidnotincludethesquarebrackets andgradesArraypointedtoanarrayofobjectsOnlythefirstobjectinthearraywouldhaveadestructorcall 64 CommonProgrammingError10 9 Usingdeleteinsteadofdelete forarraysofobjectscanleadtoruntimelogicerrors Toensurethateveryobjectinthearrayreceivesadestructorcall alwaysdeletememoryallocatedasanarraywithoperatordelete Similarly alwaysdeletememoryallocatedasanindividualelementwithoperatordelete otherwise theresultoftheoperationisundefined 65 10 7staticClassMembers staticdatamemberOnlyonecopyofavariablesharedbyallobjectsofaclass Class wide informationApropertyoftheclasssharedbyallinstances notapropertyofaspecificobjectoftheclassDeclarationbeginswithkeywordstatic 66 10 7staticClassMembers Cont staticdatamember Cont ExampleVideogamewithMartiansandotherspacecreaturesEachMartianneedstoknowthemartianCountmartianCountshouldbestaticclass widedataEveryMartiancanaccessmartianCountasifitwereadatamemberofthatMartianOnlyonecopyofmartianCountexistsMayseemlikeglobalvariablesbuttheyhaveclassscopeCanbedeclaredpublic privateorprotected 67 10 7staticClassMembers Cont staticdatamember Cont Fundamental typestaticdatamembersInitializedbydefaultto0Ifyouwantadifferentinitialvalue astaticdatamembercanbeinitializedonce andonlyonce AconststaticdatamemberofintorenumtypeCanbeinitializedinitsdeclarationintheclassdefinitionAllotherstaticdatamembersMustbedefinedatfilescope i e outsidethebodyoftheclassdefinition Canbeinitializedonlyinthosedefinitionsstaticdatamembersofclasstypes i e staticmemberobjects thathavedefaultconstructorsNeednotbeinitializedbecausetheirdefaultconstructorswillbecalled 68 10 7staticClassMembers Cont staticdatamember Cont ExistsevenwhennoobjectsoftheclassexistToaccessapublicstaticclassmemberwhennoobjectsoftheclassexistPrefixtheclassnameandthebinaryscoperesolutionoperator tothenameofthedatamemberExampleMartian martianCountAlsoaccessiblethroughanyobjectofthatclassUsetheobject sname thedotoperatorandthenameofthememberExamplemyMartian martianCount 69 10 7staticClassMembers Cont staticmemberfunctionIsaserviceoftheclass notofaspecificobjectoftheclassstaticappliedtoanitematfilescopeThatitembecomesknownonlyinthatfileThestaticmembersoftheclassneedtobeavailablefromanyclientcodethataccessesthefileSowecannotdeclarethemstaticinthe cppfile wedeclarethemstaticonlyinthe hfile 70 SoftwareEngineeringObservation10 11 Aclass sstaticdatamembersandstaticmemberfunctionsexistandcanbeusedevenifnoobjectsofthatclasshavebeeninstantiated 71 Outline fig10 21 cpp 1of1 Functionprototypeforstaticmemberfunction staticdatamemberkeepstrackofnumberofEmployeeobjectsthatcurrentlyexist 72 Outline Employee cpp 1of3 staticdatamemberisdefinedandinitializedatfilescopeinthe cppfile staticmemberfunctioncanaccessonlystaticdata becausethefunctionmightbecalledwhennoobjectsexist 73 Outline Employee cpp 2of3 Dynamicallyallocatingchararrays Non staticmemberfunction i e constructor canmodifytheclass sstaticdatamembers Deallocatingmemoryreservedforarrays 74 Outline Employee cpp 3of3 75 Outline fig10 23 cpp 1of2 Callingstaticmemberfunctionusingclassnameandbinaryscoperesolutionoperator DynamicallycreatingEmployeeswithnew Callingastaticmemberfunctionthroughapointertoanobjectoftheclass 76 Outline fig10 23 cpp 2of2 Releasingmemorytowhichapointerpoints Disconnectingapointerfromanyspaceinmemory 77 10 7staticClassMembers Cont staticmemberfunctionsCannotaccessnon staticdataormemberfunctions AstaticmemberfunctiondoesnothaveathispointerstaticdatamembersandstaticmemberfunctionsexistindependentlyofanyobjectsofaclassWhenastaticmemberfunctioniscalled theremightnotbea

温馨提示

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

评论

0/150

提交评论