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

上传人:b****8 文档编号:28178051 上传时间:2023-07-09 格式:DOCX 页数:11 大小:39.42KB
下载 相关 举报
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第1页
第1页 / 共11页
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第2页
第2页 / 共11页
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第3页
第3页 / 共11页
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第4页
第4页 / 共11页
完整word版C++编程思想 答案 第八章 其他章节请点击用户名找 hinking in C++.docx_第5页
第5页 / 共11页
点击查看更多>>
下载资源
资源描述

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

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

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

完整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’llhavetousethestandardheader).Laterintheprogram,trytoreadasecondvalueofthetimeintoyourconstandseewhathappens.

Solution:

//:

S08:

ConstTime.cpp

#include

#include

usingnamespacestd;

consttime_tnow=time(0);

intmain(){

cout<(now)<

//now=time(0);

//cout<(now)<

}

/*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模板 > 其它模板

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1