版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 电话用耳机市场发展现状调查及供需格局分析预测报告
- 纸牌游戏器具市场环境与对策分析
- 滑雪板专用袋产业深度调研及未来发展现状趋势
- 矫形护具用衬垫产业深度调研及未来发展现状趋势
- 电力业扩报装课件
- 登山套具产业规划专项研究报告
- 煤气机产业规划专项研究报告
- 眼袋修护霜市场洞察报告
- 电子烟用充电器市场洞察报告
- 第六单元 【A卷·提升卷】(含答案解析)(安徽专用)
- 2024年秋新华师大版七年级上册数学教学课件 2.3 整式课时1
- DBJ33T 1319-2024 住宅小区供配电工程技术标准
- 延长石油招聘笔试题库
- 2023-2024学年山东省潍坊市青州市、临朐县、昌邑县、诸城市、昌乐县、寿光市八年级(上)期中英语试卷
- 幼儿园课件:古诗《绝句》
- 小学教育集团三年发展规划(2024年-2027年)
- (高清版)TDT 1015.1-2024 地籍数据库 第1部分:不动产
- JT-T-1214-2018港口高杆灯技术要求
- JT-T-1168-2017公路桥梁用氟碳面漆
- T-CNFPIA 1003-2022 采暖用人造板及其制品中甲醛释放限量
- 爆破安全技术交底书
评论
0/150
提交评论