(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx

上传人:PIYPING 文档编号:10771174 上传时间:2021-06-03 格式:DOCX 页数:14 大小:297.30KB
返回 下载 相关 举报
(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第1页
第1页 / 共14页
(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第2页
第2页 / 共14页
(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第3页
第3页 / 共14页
(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第4页
第4页 / 共14页
(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第5页
第5页 / 共14页
点击查看更多>>
资源描述

《(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx》由会员分享,可在线阅读,更多相关《(完整word版)C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx(14页珍藏版)》请在三一文库上搜索。

1、ViewingHintsBookHomePageFreeNewsletterSeminarsSeminarsonCDROMConsultingAnnotatedSolutionGuideRevision1.0forThinkinginC+,2ndedition,Volume1byChuckAllison2001MindView,Inc.AllRightsReserved.PreviousChapterTableofContentsNextChapterChapter88-1Createthreeconstintvalues,thenaddthemtogethertoproduceavaluet

2、hatdeterminesthesizeofanarrayinanarraydefinition.TrytocompilethesamecodeinCandseewhathappens(youcangenerallyforceyourC+compilertorunasaCcompilerbyusingacommand-lineflag).(Lefttothereader)8-2ProvetoyourselfthattheCandC+compilersreallydotreatconstantsdifferently.Createaglobalconstanduseitinaglobalcons

3、tantexpression;thencompileitunderbothCandC+.Solution:/:S08:GlobalConst.cppconstintn=100;constintm=n+2;intmain()/:WhilethisisalegalC+program,Cdoesntallowexpressionswithconstvariablesatthegloballevel,sotheabovecodewillnotcompileinC.Ifyoumovethedeclarationofminsideofmain(),however,itworksfineinC.Butdon

4、tletthismakeyouthinkthatyoucandothisforarraydeclarations.Exercise1showsthatyoucannotuseaconstvariableasanarraydimensioninCunderanycircumstances.83Createexampleconstdefinitionsforallthebuilt-intypesandtheirvariants.Usetheseinexpressionswithotherconststomakenewconstdefinitions.Makesuretheycompilesucce

5、ssfully.(Lefttothereader)84Createaconstdefinitioninaheaderfile,includethatheaderfileintwo.cppfiles,thencompilethosefilesandlinkthem.Youshouldnotgetanyerrors.NowtrythesameexperimentwithC.(Lefttothereader)85Createaconstwhosevalueisdeterminedatruntimebyreadingthetimewhentheprogramstarts(youllhavetouset

6、hestandardheader).Laterintheprogram,trytoreadasecondvalueofthetimeintoyourconstandseewhathappens.Solution:/:S08:ConstTime.cpp#include#includeusingnamespacestd;consttime_tnow=time(0);intmain()coutstatic_cast(now)endl;/now=time(0);/coutstatic_cast(now)endl;/*Output:949180534*/:Thefirstcommentedlineisi

7、llegalbecauseyoucantassigntoconstvariablestheycanonlybeinitialized.ImadethevariablenowglobaltoemphasizeanimportantdifferencebetweenCandC+:youcaninitializeautomaticvariablesatruntimeinC,butnotglobals,likeyoucaninC+.Forexample,thefollowingCprogramworksjustfine:/:S08:ConstTime.c#include#includeintmain(

8、)consttime_tnow=time(0);printf(%ld,now);/*Output:949180534*/:Ifyoumovethedefinitionofnowoutsideofmain(),aCcompilerwillcomplain.86Createaconstarrayofchar,thentrytochangeoneofthechars.(Lefttothereader)87Createanexternconstdeclarationinonefile,andputamain()inthatfilethatprintsthevalueoftheexternconst.P

9、rovideanexternconstdefinitioninasecondfile,thencompileandlinkthetwofilestogether.(Lefttothereader)88Writetwopointerstoconstlongusingbothformsofthedeclaration.Pointoneofthemtoanarrayoflong.Demonstratethatyoucanincrementordecrementthepointer,butyoucantchangewhatitpointsto.(Lefttothereader)89Writeacons

10、tpointertoadouble,andpointitatanarrayofdouble.Showthatyoucanchangewhatthepointerpointsto,butyoucantincrementordecrementthepointer.(Lefttothereader)810Writeaconstpointertoaconstobject.Showthatyoucanonlyreadthevaluethatthepointerpointsto,butyoucantchangethepointerorwhatitpointsto.(Lefttothereader)811R

11、emovethecommentontheerror-generatinglineofcodeinPointerAssignment.cpptoseetheerrorthatyourcompilergenerates.(Lefttothereader)812Createacharacterarrayliteralwithapointerthatpointstothebeginningofthearray.Nowusethepointertomodifyelementsinthearray.Doesyourcompilerreportthisasanerror?Shouldit?Ifitdoesn

12、t,whydoyouthinkthatis?Solution:/:S08:StringLiteral.cpp#includeintmain()usingnamespacestd;char*word=hello;*word=j;coutwordendl;/*Output:jello*/:Asexplainedinthebook,eventhoughstringliteralsarearraysofconstchar,forcompatibilitywithCyoucanassignthemtoachar*(“pointertoanon-constchar”).Yourenotsupposedto

13、beabletochangeastringliteral(thestandardsaysthatanysuchattempthasundefinedresults),butmostcompilersruntheprogramabovethesame.Itscertainlynotarecommendpractice.813Createafunctionthattakesanargumentbyvalueasaconst;thentrytochangethatargumentinthefunctionbody.(Lefttothereader)814Createafunctionthattake

14、safloatbyvalue.Insidethefunction,bindaconstfloat&totheargument,andonlyusethereferencefromthenontoensurethattheargumentisnotchanged.(Lefttothereader)815ModifyConstReturnValues.cppremovingcommentsontheerror-causinglinesoneatatime,toseewhaterrormessagesyourcompilergenerates.(Lefttothereader)816ModifyCo

15、nstPointer.cppremovingcommentsontheerror-causinglinesoneatatime,toseewhaterrormessagesyourcompilergenerates.(Lefttothereader)817MakeanewversionofConstPointer.cppcalledConstReference.cppwhichdemonstratesreferencesinsteadofpointers(youmayneedtolookforwardtoChapter11).Solution:/:S08:ConstReference.cpp/

16、Constantreferencearg/returnvoidt(int&)voidu(constint&cir)inti=cir;constint&w()staticinti;returni;intmain()intx=0;int&ir=x;constint&cir=x;t(ir);/!t(cir);/NotOKu(ir);u(cir);/!int&ip2=w();/NotOKconstint&cir2=w();/!w()=1;/NotOK/:WhencomparingthisprogramtoConstPointer.cppinthebook,noticefirsttheomissiono

17、fthosestatementsthatqualifythereferenceitselfasconst.Whileyoucandeclareapointeritselftobeconst(asopposedtoapointer-to-const),allreferencesareimplicitlyconst,becauseonceboundtoanobjectyoucantchangethatbinding(moreinChapter11).Thecommented-outstatementsareallconstviolations(i.e.,youcantassignviaarefer

18、ence-to-const).8-18ModifyConstTemporary.cppremovingthecommentontheerror-causinglinetoseewhaterrormessagesyourcompilergenerates.(Lefttothereader)8-19Createaclasscontainingbothaconstandanon-constfloat.Initializetheseusingtheconstructorinitializerlist.Solution:/:S08:InitList.cpp#includeusingnamespacest

19、d;classHasFloatsconstfloatx_;floaty_;public:HasFloats(floatx,floaty):x_(x),y_(y)voiddisplay()constcoutx=x_,y=y_endl;intmain()HasFloatsh(3,4);h.display();/*Output:x=3,y=4*/:Youcaninitializey_inthebodyoftheconstructorifyouwish,butconstmemberslikex_mustbeinitializedintheinitializerlist.820Createaclassc

20、alledMyStringwhichcontainsastringandhasaconstructorthatinitializesthestring,andaprint()function.ModifyStringStack.cppsothatthecontainerholdsMyStringobjects,andmain()soitprintsthem.(Lefttothereader)821Createaclasscontainingaconstmemberthatyouinitializeintheconstructorinitializerlistandanuntaggedenume

21、rationthatyouusetodetermineanarraysize.(Lefttothereader)822InConstMember.cpp,removetheconstspecifieronthememberfunctiondefinition,butleaveitonthedeclaration,toseewhatkindofcompilererrormessageyouget.(Lefttothereader)823Createaclasswithbothconstandnon-constmemberfunctions.Createconstandnon-constobjec

22、tsofthisclass,andtrycallingthedifferenttypesofmemberfunctionsforthedifferenttypesofobjects.(Lefttothereader)824Createaclasswithbothconstandnon-constmemberfunctions.Trytocallanon-constmemberfunctionfromaconstmemberfunctiontoseewhatkindofcompilererrormessageyouget.(Lefttothereader)825InMutable.cpp,rem

23、ovethecommentontheerror-causinglinetoseewhatsortoferrormessageyourcompilerproduces.(Lefttothereader)826ModifyQuoter.cppbymakingquote()aconstmemberfunctionandlastquotemutable.Solution:Heresthemodifiedclassdefinition:/:S08:Quoter.cppO#include#include#includeusingnamespacestd;classQuotermutableintlastq

24、uote;public:Quoter();intlastQuote()const;constchar*quote()const;/:addaDontforgettoconstsuffixtothedefinitionofQuoter:quote()also.Nootherchangesarenecessary.8-27Createaclasswithavolatiledatamember.Createbothvolatileandnon-volatilememberfunctionsthatmodifythevolatiledatamember,andseewhatthecompilersay

25、s.Createbothvolatileandnon-volatileobjectsofyourclassandtrycallingboththevolatileandnon-volatilememberfunctionstoseewhatissuccessfulandwhatkindoferrormessagesthecompilerproduces.Solution:/:S08:Volatile.cppclassVolatilevolatileintx;public:voidmod1(intx)this-x=x;voidmod2(intx)volatilethis-x=x;intmain(

26、)Volatilev1;volatileVolatilev2;v1.mod1(1);v1.mod2(2);/!v2.mod1(3);/Errorv2.mod2(4);/:Theonlyerrorisinattemptingtocallanon-volatilefunctionforavolatileobject.Youmightthinkthatmod1()wouldhavetroublecompiling,butitdoesnt.volatileisnotexactlythesameasconst.Justrememberthatvolatilemeansthatsomethingoutsi

27、dewhatisvisibleinthesourcecodemaymodifyanobject(andsovolatiledeclarationsusuallyarepointers).Theresnoproblemwithyourcodealsomodifyingavolatileobjectlikemod1()does.8-28Createaclasscalledbirdthatcanfly()andaclassrockthatcant.Createarockobject,takeitsaddress,andassignthattoavoid*.Nowtakethevoid*,assign

28、ittoabird*(youllhavetouseacast),andcallfly()throughthatpointer.IsitclearwhyCspermissiontoopenlyassignviaavoid*(withoutacast)isa“hole”inthelanguage,whichcouldntbepropagatedintoC+?Solution:ThisisthewholepointofC+stypesystem!Youshouldntbeabletoaccidentallymisuseanobjectthroughpointergyrations.Ifthiswereallowed,youcouldindirectlycallanyfunctionatallforanyobjectatallwithoutthecompilercomplaining.Notasmartwaytoprogram.PreviousChapterTableofContentsNextChapterLastUpdate:06/27/2002

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 科普知识


经营许可证编号:宁ICP备18001539号-1