C++编程思想-答案-第十一章-其他章节点击用户名找-thinking-in-C++-annotat

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

[ViewingHints][BookHomePage][FreeNewsletter][Seminars][SeminarsonCDROM][Consulting]AnnotatedSolutionGuideRevision1.0forThinkinginC++,2ndedition,Volume1byChuckAllison©2001MindView,Inc.AllRightsReserved.[PreviousChapter][TableofContents][NextChapter]Chapter1111-1Turnthe“bird&rock”codefragmentatthebeginningofthischapterintoaCprogram(usingstructsforthedatatypes),andshowthatitcompiles.NowtrytocompileitwiththeC++compilerandseewhathappens.(Lefttothereader)11-2Takethecodefragmentsinthebeginningofthesectiontitled“ReferencesinC++”andputthemintoamain().Addstatementstoprintoutputsothatyoucanprovetoyourselfthatreferencesarelikepointersthatareautomaticallydereferenced.(Lefttothereader)11-3Writeaprograminwhichyoutryto(1)Createareferencethatisnotinitializedwhenitiscreated.(2)Changeareferencetorefertoanotherobjectafteritisinitialized.(3)CreateaNULLreference.(Lefttothereader)11-4Writeafunctionthattakesapointerargument,modifieswhatthepointerpointsto,andthenreturnsthedestinationofthepointerasareference.(Lefttothereader)11-5Createaclasswithsomememberfunctions,andmakethattheobjectthatispointedtobytheargumentofExercise4.Makethepointeraconstandmakesomeofthememberfunctionsconstandprovethatyoucanonlycalltheconstmemberfunctionsinsideyourfunction.Maketheargumenttoyourfunctionareferenceinsteadofapointer.(Lefttothereader)11-6Takethecodefragmentsatthebeginningofthesectiontitled“Pointerreferences”andturnthemintoaprogram.(Lefttothereader)11-7Createafunctionthattakesanargumentofareferencetoapointertoapointerandmodifiesthatargument.Inmain(),callthefunction.(Lefttothereader)11-8Createafunctionthattakesachar&argumentandmodifiesthatargument.Inmain(),printoutacharvariable,callyourfunctionforthatvariable,andprintitoutagaintoprovetoyourselfthatithasbeenchanged.Howdoesthisaffectprogramreadability?Solution://:S11:CallByRef.cpp#includeiostreamvoidnextc(char&c){staticcharletter='a';c=letter++;}intmain(){usingnamespacestd;charc='z';coutc==cendl;nextc(c);coutc==cendl;nextc(c);coutc==cendl;}/*Output:c==zc==ac==b*////:~ACprogrammerwillfinditverystrangeindeedthatcischangedinmain(),sinceapointerwasn’tpassed.Pass-by-referencesemanticshavesideeffectsandshouldbeusedsparingly.Agoodexampleisistream::get(char&c).Sincestreamfunctionsreturnareferencetothestreamitselfsoyoucanimmediatelytestitforend-of-file,thecharacterextractedfromtheinputstreamisstoredviathereferenceargumentc.11-9Writeaclassthathasaconstmemberfunctionandanon-constmemberfunction.Writethreefunctionsthattakeanobjectofthatclassasanargument;thefirsttakesitbyvalue,thesecondbyreference,andthethirdbyconstreference.Insidethefunctions,trytocallbothmemberfunctionsofyourclassandexplaintheresults.(Lefttothereader)11-10(Somewhatchallenging)Writeasimplefunctionthattakesanintasanargument,incrementsthevalue,andreturnsit.Inmain(),callyourfunction.Nowdiscoverhowyourcompilergeneratesassemblycodeandtracethroughtheassemblystatementssothatyouunderstandhowargumentsarepassedandreturned,andhowlocalvariablesareindexedoffthestack.(Lefttothereader)11-11Writeafunctionthattakesasitsargumentsachar,int,float,anddouble.Generateassemblycodewithyourcompilerandfindthestatementsthatpushtheargumentsonthestackbeforeafunctioncall.(Lefttothereader)11-12Writeafunctionthatreturnsadouble.Generateassemblycodeanddeterminehowthevalueisreturned.(Lefttothereader)11-13ProduceassemblycodeforPassingBigStructures.cpp.Tracethroughanddemystifythewayyourcompilergeneratescodetopassandreturnlargestructures.(Lefttothereader)11-14Writeasimplerecursivefunctionthatdecrementsitsargumentandreturnszeroiftheargumentbecomeszero,otherwiseitcallsitself.Generateassemblycodeforthisfunctionandexplainhowthewaythattheassemblycodeiscreatedbythecompilersupportsrecursion.(Lefttothereader)11-15Writecodetoprovethatthecompilerautomaticallysynthesizesacopy-constructorifyoudon’tcreateoneyourself.Provethatthesynthesizedcopy-constructorperformsabitcopyofprimitivetypesandcallsthecopy-constructorofuser-definedtypes.Solution://:S11:AutoCopy.cpp#includeiostreamusingnamespacestd;classInner{doublex;public:Inner(doublex){this-x=x;}Inner(constInner&i2){x=i2.x;coutInner::Inner(constInner&)\n;}doublegetX()const{returnx;}};classOuter{Innerm;intn;public:Outer(doublex,inti):m(x),n(i){}voidprint(){cout'('m.getX()','n)\n;}};intmain(){Outero1(10.0,20);o1.print();Outero2(o1);o2.print();}/*Output:(10,20)Inner::Inner(constInner&)(10,20)*////:~ClassOutercontainsaninstanceofclassInnerandanint,butithasnocopyconstructor,sothecompilerwillbuildoneforus.ClassInnerhasacopyconstructorthatannouncesitselfsoyoucanseethatitexecutes,andthesubsequentcalltoOuter::print()alsorevealsthattheintmemberwascopiedcorrectly.11-16Writeaclasswithacopy-constructorthatannouncesitselftocout.Nowcreateafunctionthatpassesanobjectofyournewclassinbyvalueandanotheronethatcreatesalocalobjectofyournewclassandreturnsitbyvalue.Callthesefunctionstoprovetoyourselfthatthecopy-constructorisindeedquietlycalledwhenpassingandreturningobjectsbyvalue.Solution://:S11:TraceCopies.cpp#includeiostreamusingnamespaces

1 / 24
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功