C++面向对象程序设计双语教程(第3版)课件 ch04Advance of Classes and Objects-Further Definition of Class Members and Objects_第1页
C++面向对象程序设计双语教程(第3版)课件 ch04Advance of Classes and Objects-Further Definition of Class Members and Objects_第2页
C++面向对象程序设计双语教程(第3版)课件 ch04Advance of Classes and Objects-Further Definition of Class Members and Objects_第3页
C++面向对象程序设计双语教程(第3版)课件 ch04Advance of Classes and Objects-Further Definition of Class Members and Objects_第4页
C++面向对象程序设计双语教程(第3版)课件 ch04Advance of Classes and Objects-Further Definition of Class Members and Objects_第5页
已阅读5页,还剩38页未读 继续免费阅读

下载本文档

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

文档简介

AdvanceofClassesandObjects—FurtherDefinitionofClassMembersandObjectsC++面向对象程序设计双语教程(第3版)Chapter401ConstantMemberFunctionsandConstantObjectsTheDateclassdefinedsofarprovidesmemberfunctionsinordertogiveaDateobjectvaluesandchangeit.Unfortunately,wedidnotprovideawayofexaminingthevalueofaDate.Thisproblemcaneasilyberemediedbyaddingfunctionsforreadingtheday,month,andyear.ConstantMemberFunctionsandConstantObjectsNoteTheconstkeywordisplacedafterthe(empty)parameterlistinthefunctiondeclarations.It

indicatesthatthesefunctionseannotmodifythedatacontentofaDateclass.const关键字放置在函数声明中的(空)参数列表之后,它表示这些函数不能修改Date类的数据内容。ConstantMemberFunctionsandConstantObjectsSomeobjectsneedtobemodifiableandsomenot.Theconstkeywordcanbeusedtospecifythatanobjectisnotmodifiableandthatanyattempttomodifytheobjectshouldresultinacompilationerror.Aconstmemberfunctioncanbeinvokedforbothconstandnon-constobjects,whereasanon-constmemberfunctioncanbeinvokedonlyfornon-constobjects.ConstantMemberFunctionsandConstantObjects02thisPointersAnyobjecthasaccesstoitsownaddressthroughapointercalledthis.Butthethispointer

ofanobjectisnotpartoftheobjectsitself-i.e.thesizeofthememorytakenbythethispointerdoesnotaffecttheresultofasizeofoperationontheobjects.Forexample,boththesizesofthetodayandtomorrowobjeetsare12inthisexample.thisPointersWhenanon-staticmemberfunctioniscalledforanobjeet,thethispointerispassedasanimplicitargumenttoeachofthenon-staticmemberfunctionsofaclass,struct,oruniontype.However,staticmemberfunctionsdonothaveathispointer.thisPointersTheobject'saddressisavailablewithinthememberfunctionasthethispointer.Mostusagesofthisareimplicit.Itislegal,thoughunnecessary,toexplicitlyusethiswhenreferringtomembersoftheclass.thisPointersThethispointerisnotanordinaryvariable.Becausethethispointerisnon-modifiable,assignmentsto

this

are

not

allowed.this指针不是普通的变量。因为this指针是不可修改的,所以不允许给this指针赋值。thisPointers03StaticMembersInsideaclassdefinition,theclassmemberscanbedeclaredusingthestorageclassspecifierstatieintheclassmemberlist.Staticmembersofaclassarenotassociatedwiththeobjectsoftheclass:theyareindependentvariableswithstaticstorageduration.StaticMembersAstaticmemberisavariablethatispartofaclass,yetisnotpartofanobjectofthatclass.Onlyone

copyofthestaticmemberissharedbyallobjectsofaclassinaprogram.静态成员是一个类的部分的变量,但不是该类对象的一部分。程序中一个类的所有对象只共享静态成员的一个副本。StaticMembersAtypicaluseofstaticmembersisforrecordingdatacommontoallobjectsofaclass.Forexample,youcanuseastaticdatamemberasacountertostorethenumberofobjectsofaparticularclasstypethatarecreated.Eachtimeanewobjectiscreated,thisstaticdatamember

canbeincrementedtokeeptrackofthetotalnumberofobjects.StaticMembersWhenweinstantiateaclassobject,eachobjectgetsitsowncopyofallnormaldatamembers.Inthiscase,sincewehavedeclaredthreestudentclassobjects,weendupwiththreecopiesofcountoneinsidestl,thesecondinsidest2,andthethirdinsidest3.Theyshouldhavedifferentvaluesbecausethecountvariableisusedtokeeptrackofthetotalnumberof

objects.However,theygetthesamevalue0.StaticMembers04FreeStoreThefreestoreisapoolofmemoryavailableforyoutoalloeate(anddeallocate)storageforobjectsduringtheexecutionofyourprogram.Thenewanddeleteoperatorsareusedtoallocateanddeallocatefreestore,respectively.FreeStoreWhenyouaredonewithyourareaofmemory,youmustcallthedeletestatementonthepointer.Thedeletestatementreturnsthememorytothefreestore.Rememberthatthepointeritselfasopposedtothememorytowhichitpoints--isalocalvariable.Whenthefunctionin

whichitisdeclaredreturns,thatpointergoesoutofscopeandislost.FreeStoreThememoryallocated

byusingnewisnotfreedautomatically,however.Thatmemorybecomesunavailablea

situationcalledamemoryleak.Thenameisgiventodeseribethatthepartofmemorycannotberecovereduntiltheprogramends.Itisasthoughthememoryhasleakedoutofyourcomputer.FreeStoreJustasyoucancreateapointertoaninteger,youcancreateapointertoanyobject.IfyouhavedeclaredanobjectofclassDate,youcandeclareapointertothatclassandinstantiateaDateobjectonthefreestore,justasyoucanmakeoneonthestack.FreeStore05ObjectMembersDefinitionofObjectMembersSometimes,aclasshasadatamemberwhichisnotasimplebuilt-indatatypebutanaggregatebuilt-indata.Suchdatamemberisdefinedasanotherclassobject.Whenaclasshasobjectsofotherclassesasmembers,suchcapabilityiscalledcomposition.Compositionisaspecialcaseoftheaggregationrelationship.ObjectMembersForcreatingobjects,themembers

constructorsareinvokedbeforethebodyofthecontainingclass'ownconstructorisexecuted.Theconstructorsareinvokedintheorderinwhichthemembersaredeclaredintheclassratherthantheorderinwhichthemembersappear

intheinitializationlist.TheOrderofConstructorsandDestructorsforMemberObjectsObjectMembers为了确保成员对象的初始化要求,必须满足下列条件之一:包含对象的类不需要构造函数。包含对象的类有一个可访问的默认构造函数。包含类的构造函数都显式地初始化包含的对象。ObjectMembersClassMembersbyUsingInitializersMemberinitializersareessentialfortypesforwhichinitializationdiffersfromtheassignment,thatis,formemberobjectsofclasseswithoutadefaultconstructor,forconstmembers,andforreferencemembers.ObjectMembers06CopyMembersThecopyconstructortakesareferencetoaconstparameter.Itisaconsttoguaranteethatthecopyconstructordoesnotchangeit.Inaddition,itisareferencebecauseavalueparameterwouldrequiremakingacopy,whichwouldinvokethecopyconstructor,thereforemakinga

copyofitsparameter.CopyMembersDefinitionofCopyConstructorsTheaboveisanexampleofacopyconstructorfortheDateclass,whichdoesnotreallyneedonebecausethedefaultcopyconstructor'sactionofcopyingdatawouldworkfine.Still,itshowshowitworks.CopyMembersDefinitionofCopyConstructorsShallowCopyAshallowcopymeansthatC++copieseachmemberoftheclassindividuallyusingtheassignmentoperator(=).Whenclassesaresimple

e.g.donotcontainanydynamically

allocatedmemory),thisworksverywellliketheexampleabove.CopyMembersDeepCopyTherootofthisproblemistheshallowcopydonebythecopyconstructordoingashallowcopyonpointervaluesinaeopyconstructororanoverloadedassignmentoperator(=)usuallymeanstrouble.Thesolutiontothisproblemistodoadeepcopyonanynon-null

pointersbeingcopied.CopyMembers07ArraysofObjectsInitializeanObjectArraybyUsingaDefaultConstructorSupposethatyoudeclareanarrayof4classobjects,forexample,4Dateobjects.youneedtodisplaytheirdays,monthsandyears.YouhavetodeclareonearrayarrayDateof4elementseach,whereineachelementisanobjectoftypeDate.ArraysofObjectsInitializeanObjectArraybyUsingaDefaultConstructorInthisease,itisimpracticaltospecifydifferentconstructorsforeachelement.Therefore,thedefaultconstructorisusedtoinitializeeach(array)classobject.Ifaclasshasconstructorsandyoudeclareanobjeetofthatclass,theclassshouldhavethedefaultconstructor.ArraysofObjects08FriendsAsdiscussedintheprevioussectionsonaccessspecifiers,toaccessdatamembersday,monthandyearfromtheoutsideoftheclassbythemainfunction,thedatamembersaredeclaredasprivateinsidetheDateclassinthepreviousexamples,becausethemainfunctionisnotaclassmemberthatwillnotbeabletoaceesstheprivatedata.FriendsToaccesstheprivatedatamembers,datamembersareputintothepublicpartoftheclass.However,thisbreakstheinformationhidingoftheclass.Infact,aprogrammermayhaveasituationwhereheorshewouldneedtoaccessprivatedatafromnon-memberfunctions.Forhandlingsuchcases,the

conceptoffriendfunetionsisausefultool.FriendsAfriendofaclassisafunetionorclassthatisnotamemberoftheclass,butisgrantedthesameaccess

totheclassasthemembersoftheclass.类的友元是一个函数或类,它不是类的成员,但是被赋予与类的成员相同的访问权。FriendsFunct

温馨提示

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

评论

0/150

提交评论