您好,欢迎访问三七文档
[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
本文标题:C++编程思想-答案-第十一章-其他章节点击用户名找-thinking-in-C++-annotat
链接地址:https://www.777doc.com/doc-4778839 .html