完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx
- 文档编号:28178051
- 上传时间:2023-07-09
- 格式:DOCX
- 页数:11
- 大小:39.42KB
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx
《完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx》由会员分享,可在线阅读,更多相关《完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx(11页珍藏版)》请在冰豆网上搜索。
完整word版C++编程思想答案第八章其他章节请点击用户名找hinkinginC++
[ViewingHints][BookHomePage][FreeNewsletter]
[Seminars][SeminarsonCDROM][Consulting]
AnnotatedSolutionGuide
Revision1.0
forThinkinginC++,2ndedition,Volume1
byChuckAllison
©2001MindView,Inc.AllRightsReserved.
[PreviousChapter][TableofContents][NextChapter]
Chapter8
8-1
Createthreeconstintvalues,thenaddthemtogethertoproduceavaluethatdeterminesthesizeofanarrayinanarraydefinition.TrytocompilethesamecodeinCandseewhathappens(youcangenerallyforceyourC++compilertorunasaCcompilerbyusingacommand-lineflag).
(Lefttothereader)
8-2
ProvetoyourselfthattheCandC++compilersreallydotreatconstantsdifferently.Createaglobalconstanduseitinaglobalconstantexpression;thencompileitunderbothCandC++.
Solution:
//:
S08:
GlobalConst.cpp
constintn=100;
constintm=n+2;
intmain(){
}///:
~
WhilethisisalegalC++program,Cdoesn’tallowexpressionswithconstvariablesatthegloballevel,sotheabovecodewillnotcompileinC.Ifyoumovethedeclarationofminsideofmain(),however,itworksfineinC.Butdon’tletthismakeyouthinkthatyoucandothisforarraydeclarations.Exercise1showsthatyoucannotuseaconstvariableasanarraydimensioninCunderanycircumstances.
8-3
Createexampleconstdefinitionsforallthebuilt-intypesandtheirvariants.Usetheseinexpressionswithotherconststomakenewconstdefinitions.Makesuretheycompilesuccessfully.
(Lefttothereader)
8-4
Createaconstdefinitioninaheaderfile,includethatheaderfileintwo.cppfiles,thencompilethosefilesandlinkthem.Youshouldnotgetanyerrors.NowtrythesameexperimentwithC.
(Lefttothereader)
8-5
Createaconstwhosevalueisdeterminedatruntimebyreadingthetimewhentheprogramstarts(you’llhavetousethe
Solution:
//:
S08:
ConstTime.cpp
#include
#include
usingnamespacestd;
consttime_tnow=time(0);
intmain(){
cout< //now=time(0); //cout< } /*Output: 949180534 */ ///: ~ Thefirstcommentedlineisillegalbecauseyoucan’tassigntoconstvariables–theycanonlybeinitialized.ImadethevariablenowglobaltoemphasizeanimportantdifferencebetweenCandC++: youcaninitializeautomaticvariablesatruntimeinC,butnotglobals,likeyoucaninC++.Forexample,thefollowingCprogramworksjustfine: //: S08: ConstTime.c #include #include intmain(){ consttime_tnow=time(0); printf("%ld",now); } /*Output: 949180534 */ ///: ~ Ifyoumovethedefinitionofnowoutsideofmain(),aCcompilerwillcomplain. 8-6 Createaconstarrayofchar,thentrytochangeoneofthechars. (Lefttothereader) 8-7 Createanexternconstdeclarationinonefile,andputamain()inthatfilethatprintsthevalueoftheexternconst.Provideanexternconstdefinitioninasecondfile,thencompileandlinkthetwofilestogether. (Lefttothereader) 8-8 Writetwopointerstoconstlongusingbothformsofthedeclaration.Pointoneofthemtoanarrayoflong.Demonstratethatyoucanincrementordecrementthepointer,butyoucan’tchangewhatitpointsto. (Lefttothereader) 8-9 Writeaconstpointertoadouble,andpointitatanarrayofdouble.Showthatyoucanchangewhatthepointerpointsto,butyoucan’tincrementordecrementthepointer. (Lefttothereader) 8-10 Writeaconstpointertoaconstobject.Showthatyoucanonlyreadthevaluethatthepointerpointsto,butyoucan’tchangethepointerorwhatitpointsto. (Lefttothereader) 8-11 Removethecommentontheerror-generatinglineofcodeinPointerAssignment.cpptoseetheerrorthatyourcompilergenerates. (Lefttothereader) 8-12 Createacharacterarrayliteralwithapointerthatpointstothebeginningofthearray.Nowusethepointertomodifyelementsinthearray.Doesyourcompilerreportthisasanerror? Shouldit? Ifitdoesn’t,whydoyouthinkthatis? Solution: //: S08: StringLiteral.cpp #include intmain(){ usingnamespacestd; char*word="hello"; *word='j'; cout< } /*Output: jello */ ///: ~ Asexplainedinthebook,eventhoughstringliteralsarearraysofconstchar,forcompatibilitywithCyoucanassignthemtoachar*(“pointertoanon-constchar”).You’renotsupposedtobeabletochangeastringliteral(thestandardsaysthatanysuchattempthasundefinedresults),butmostcompilersruntheprogramabovethesame.It’scertainlynotarecommendpractice. 8-13 Createafunctionthattakesanargumentbyvalueasaconst;thentrytochangethatargumentinthefunctionbody. (Lefttothereader) 8-14 Createafunctionthattakesafloatbyvalue.Insidethefunction,bindaconstfloat&totheargument,andonlyusethereferencefromthenontoensurethattheargumentisnotchanged. (Lefttothereader) 8-15 ModifyConstReturnValues.cppremovingcommentsontheerror-causinglinesoneatatime,toseewhaterrormessagesyourcompilergenerates. (Lefttothereader) 8-16 ModifyConstPointer.cppremovingcommentsontheerror-causinglinesoneatatime,toseewhaterrormessagesyourcompilergenerates. (Lefttothereader) 8-17 MakeanewversionofConstPointer.cppcalledConstReference.cppwhichdemonstratesreferencesinsteadofpointers(youmayneedtolookforwardtoChapter11). Solution: //: S08: ConstReference.cpp //Constantreferencearg/return voidt(int&){} voidu(constint&cir){ inti=cir; } constint&w(){ staticinti; returni; } intmain(){ intx=0; int&ir=x; constint&cir=x; t(ir); //! t(cir);//NotOK u(ir); u(cir); //! int&ip2=w();//NotOK constint&cir2=w(); //! w()=1;//NotOK }///: ~ WhencomparingthisprogramtoConstPointer.cppinthebook,noticefirsttheomissionofthosestatementsthatqualifythereferenceitselfasconst.Whileyoucandeclareapointeritselftobeconst(asopposedtoapointer-to-const),allreferencesareimplicitlyconst,becauseonceboundtoanobjectyoucan’tchangethatbinding(moreinChapter11).Thecommented-outstatementsareallconstviolations(i.e.,youcan’tassignviaareference-to-const). 8-18 ModifyConstTemporary.cppremovingthecommentontheerror-causinglinetoseewhaterrormessagesyourcompilergenerates. (Lefttothereader) 8-19 Createaclasscontainingbothaconstandanon-constfloat.Initializetheseusingtheconstructorinitializerlist. Solution: //: S08: InitList.cpp #include usingnamespacestd; classHasFloats{ constfloatx_; floaty_; public: HasFloats(floatx,floaty) : x_(x),y_(y) {} voiddisplay()const{ cout<<"x=="< } }; intmain(){ HasFloatsh(3,4); h.display(); } /*Output: x==3,y==4 */ ///: ~ Youcaninitializey_inthebodyoftheconstructorifyouwish,butconstmemberslikex_mustbeinitializedintheinitializerlist. 8-20 CreateaclasscalledMyStringwhichcontainsastringandhasaconstructorthatinitializesthestring,andaprint()function.ModifyStringStack.cppsothatthecontainerholdsMyStringobjects,andmain()soitprintsthem. (Lefttothereader) 8-21 Createaclasscontainingaconstmemberthatyouinitializeintheconstructorinitializerlistandanuntaggedenumerationthatyouusetodetermineanarraysize. (Lefttothereader) 8-22 InConstMember.cpp,removetheconstspecifieronthememberfunctiondefinition,butleaveitonthedeclaration,toseewhatkindofcompilererrormessageyouget. (Lefttothereader) 8-23 Createaclasswithbothconstandnon-constmemberfunctions.Createconstandnon-constobjectsofthisclass,andtrycallingthedifferenttypesofmemberfunctionsforthedifferenttypesofobjects. (Lefttothereader) 8-24 Createaclasswithbothconstandnon-constmemberfunctions.Trytocallanon-constmemberfunctionfromaconstmemberfunctiontoseewhatkindofcompilererrormessageyouget. (Lefttothereader) 8-25 InMutable.cpp,removethecommentontheerror-causinglinetoseewhatsortoferrormessageyourcompilerproduces. (Lefttothereader) 8-26 ModifyQuoter.cppbymakingquote()aconstmemberfunctionandlastquotemutable. Solution: Here’sthemodifiedclassdefinition: //: S08: Quoter.cpp{O} #include #include #include usingnamespacestd; classQuoter{ mutableintlastquote; public: Quoter(); intlastQuote()const; constchar*quote()const; };///: ~ Don’tforgettoaddaconstsuffixtothedefinitionofQuoter: : quote()also.Nootherchangesarenecessary. 8-27 Createaclasswithavolatiledatamember.Createbothvolatileandnon-volatilememberfunctionsthatmodifythevolatiledatamember,andseewhatthecompilersays.Createbothvolatileandnon-volatileobjectsofyourclassandtrycallingboththevolatileandnon-volatilememberfunctionstoseewhatissuccessfulandwhatkindoferrormessagesthecompilerproduces. Solution: //: S08: Volatile.cpp classVolatile{ volatileintx; public: voidmod1(intx){ this->x=x; } voidmod2(intx)volatile{ this->x=x; } }; intmain(){ Volatilev1; volatileVolatilev2; v1.mod1 (1); v1.mod2 (2); //! v2.mod1(3);//Error v2.mod2(4); }///: ~ Theonlyerrorisinattemptingtocallanon-volatilefunctionforavolatileobject.Youmightthinkthatmod1()wouldhavetroublecompilin
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 完整word版C+编程思想 答案 第八章 其他章节请点击用户名找 hinking in C+ 完整 word 编程 思想 第八 其他 章节 点击 用户名
![提示](https://static.bdocx.com/images/bang_tan.gif)
链接地址:https://www.bdocx.com/doc/28178051.html