资源描述:
《c指针和引用的使用浅谈》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、C++指针和引用的使用浅谈TheessenceandsoulofClanguageis〃pointer",butitiseasiertomakemistakeswhenusingit.C++introducestheconceptof'"reference〃・Manypeopledon,tunderstandthedifferencebetweenthem.Iwillgivesomeexamplesofprogrammingandexplainthedifferencesbetweentheminthelightofmyownexperienee.A.Commonvariablestor
2、ageBeforeweintroducepointers,let'slookatthewayordinaryvariablesarestoredinthesystem・Seethefollowingprocedure・Voidmain(void)Intia=12;IntIB=45;Lout&ia:&ia,la:,ia,endl;Cout〃&ib:〃〃&ib〃,〃Ib:〃,〃IB〃,〃endl〃;Return;Afterdefiningtwovariablesintheprogram,IAandIB,thesystemallocatestwoaddressspacestomemoryvar
3、iablesinthememoryaddress・Thecontentintheaddressisthevalueofthevariable・Theresultoftheprogramisasfollows:(Note:theaddressbelowisrandomandmaybedifferentfromtheresultofthereader)&ia:0x0012FF7C,la:12&ib:0x0012FF7&IB:45Visible:iacorrespondingmemoryaddressis:0x0012FF7C,andthisaddresscontentis12IBcorres
4、pondstothememoryaddressof:0x0012FF78,andthisaddresscontentis45Theordinaryvariable,initsassignedaddressspace,isitsvalue.Two.ThestorageofpointervariablesCompileexecutionVoidmain(void)Intia二12;Cout〃&ia:〃〃仃•〃〃Ia:〃,〃•〃〃11〃la,endl;Cout〃&ib:〃Ib:〃,〃IB〃,“endl〃;Int,*ipl,*ip2;IP1:二&ia;IP2:二&ib;Cout〃&ipl:〃,〃
5、&ipT,ipl::〃,〃*ipl:〃,*ipl,endl;Cout〃&ip2:〃,〃&ip2‘",〃ip2::〃,〃IP2〃,〃*ipl:〃,*ipl,endl;Wedefinedtwopointerstointegertypes,IP1,IP2,sothattheypointtoIAandIBrespectively,outputtheirrespectiveaddressinmemory,thepointervalue,andthevalueintheaddresstowhichthepointerpoints.Theexecutionoftheprogramresultsasfo
6、llows:&ia:0x0012FF7C,la:12&ib:0x0012FF7&IB:45&ipl:0x0012FF74,ipl:0x0012FF7C,*ipl:12&ip2:0x0012FF70,ip2:0x0012FF78,*ipl:12WefoundthattheaddressesofIP1andIP2aredifferentfromthoseofIAandIB,indicatingthatpointervariables,likeothervariables,havetheirownseparateaddressspace・Thepointer'svalueisexactlyan
7、addressthatistheaddressoftheIAandIBvariables・ThevaluesintheaddressarethevaluesofIAandIB.Nowweunderstand・Itturnedoutthatpointervariables,likeallothervariables,havetheirownseparateaddressspace,Thevalueinitisnotanactualva