C++编程思想 答案 第十章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 10Word文档下载推荐.docx
- 文档编号:22095026
- 上传时间:2023-02-02
- 格式:DOCX
- 页数:19
- 大小:42.79KB
C++编程思想 答案 第十章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 10Word文档下载推荐.docx
《C++编程思想 答案 第十章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 10Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《C++编程思想 答案 第十章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 10Word文档下载推荐.docx(19页珍藏版)》请在冰豆网上搜索。
Fibonacci.cpp
#include<
iostream>
cassert>
intfib(boolreset=false){
staticintfirst=0;
staticintsecond=1;
staticintcount=0;
if(reset){
//Startover
first=count=0;
second=1;
}
//Thefirst2numbersarespecial
intresult;
if(count==0){
assert(first==0&
&
second==1);
result=0;
elseif(count==1){
result=1;
else{
result=first+second;
first=second;
second=result;
++count;
returnresult;
}
intmain(){
usingnamespacestd;
//Printfirst10
for(inti=0;
i<
10;
++i)
cout<
<
fib()<
'
;
endl;
//printfirst5
fib(true)<
for(intj=1;
j<
5;
++j)
/*Output:
0112358132134
01123
*/
///:
~
TheFibonaccisequenceisthesequencebeginningwith0and1whereeachsuccessivenumberisthesumoftheprecedingtwo.Whenrequestingthefirstorsecondelementinthesequence(i.e.,0or1),nosummingisdone.IkeeptrackofthewhichnumberI’monwiththestaticvariablecount(thefirstnumberbeingthe“zeroeth”element).Sincethisisachapteronnamespaces,Iputtheusingdirectiveinmain(),givingittheminimalscopepossible.
10-3
Createaclassthatholdsanarrayofints.Setthesizeofthearrayusingstaticconstintinsidetheclass.Addaconstintvariable,andinitializeitintheconstructorinitializerlist;
maketheconstructorinline.Addastaticintmembervariableandinitializeittoaspecificvalue.Addastaticmemberfunctionthatprintsthestaticdatamember.Addaninlinememberfunctioncalledprint()toprintoutallthevaluesinthearrayandtocallthestaticmemberfunction.Exercisethisclassinmain().
10-4
CreateaclasscalledMonitorthatkeepstrackofthenumberoftimesthatitsincident()memberfunctionhasbeencalled.Addaprint()memberfunctionthatdisplaysthenumberofincidents.Nowcreateaglobalfunction(notamemberfunction)containingastaticMonitorobject.Eachtimeyoucallthefunctionitshouldcalltheprint()memberfunctiontodisplaytheincidentcount.Exercisethefunctioninmain().
Monitor1.cpp
classMonitor{
intcount;
public:
Monitor(){
count=0;
voidincident(){
voidprint(){
std:
:
cout<
count<
"
incidents\n"
};
voidf(){
staticMonitorm;
m.incident();
m.print();
f();
1incidents
2incidents
3incidents
4incidents
5incidents
Justlikestaticbuilt-ins,localstaticobjectsareinitializedonceduringprogramstartupanddestroyedatprogramexit.
10-5
ModifytheMonitorclassfromExercise4sothatyoucandecrement()theincidentcount.MakeaclassMonitor2thattakesasaconstructorargumentapointertoaMonitor1,andwhichstoresthatpointerandcallsincident()andprint().InthedestructorforMonitor2,calldecrement()andprint().NowmakeastaticobjectofMonitor2insideafunction.Insidemain(),experimentwithcallingthefunctionandnotcallingthefunctiontoseewhathappenswiththedestructorofMonitor2.
Monitor2.cpp
classMonitor1{
Monitor1(){
++count;
voiddecrement(){
--count;
classMonitor2{
Monitor1*pm;
Monitor2(Monitor1*p){
assert(p);
pm=p;
pm->
incident();
pm->
print();
~Monitor2(){
assert(pm);
decrement();
Monitor1g_mon;
staticMonitor2m(&
g_mon);
0incidents
FirstnoticethattheMonitor1objectneedstobeofstaticstorageduration,sinceitisusedtoinitializeastaticobject,soImadeitglobal.Becauseg_monisstatic,thereisonlyonecalltoitsconstructoranddestructor,nomatterhowmanytimestheloopinmain()executes.Butifyounevercallf(),theng_monisnotinitializedatall!
(Tryit!
).Thisillustratesthefactthatstaticobjectsareonlycreatedasneeded(soC++compilersneedtobeverysmart!
).
10-6
MakeaglobalobjectofMonitor2andseewhathappens.
Monitor3.cpp
Monitor1g_mon1;
Monitor2g_mon2(&
g_mon1);
Sincethereisnodependencyonanyfunction,butrathertheobjectsareglobal,thentheconstructoranddestructoralwaysexecuteonce.
10-7
Createaclasswithadestructorthatprintsamessageandthencallsexit().Createaglobalobjectofthisclassandseewhathappens.
10-8
InStaticDestructors.cpp,experimentwiththeorderofconstructoranddestructorcallsbycallingf()andg()insidemain()indifferentorders.Doesyourcompilergetitright?
10-9
InStaticDestructors.cpp,testthedefaulterrorhandlingofyourimplementationbyturningtheoriginaldefinitionofoutintoanexterndeclarationandputtingtheactualdefinitionafterthedefinitionofa(whoseObjconstructorsendsinformationtoout).Makesurethere’snothingelseimportantrunningonyourmachinewhenyouruntheprogramorthatyourmachinewillhandlefaultsrobustly.
10-10
Provethatfilestaticvariablesinheaderfilesdon’tclashwitheachotherwhenincludedinmorethanonecppfile.
Here’stheheaderfile:
FileStatic.h
staticintvar;
EachofthefollowingtwocppfilesincludeFileStatic.h,andcontainsfunctionsthataccessvar.
FileStatic1.cpp{O}
#include"
FileStatic.h"
voidsetVal1(intx){
var=x;
intgetVal1(){
returnvar;
}///:
FileStatic2.cpp{O}
voidsetVal2(intx){
intgetVal2(){
Ifvarhadexternallinkage,thenthefollowingmain(),whichlinkswithbothoftheprecedingcppfiles,wouldcausealinkerror(butitdoesn’t).
DifferentStatics.cpp
//{L}FileStatic1FileStatic2
externvoidsetVal1(int);
externvoidsetVal2(int);
externintgetVal1();
externintgetVal2();
setVal1
(1);
setVal2
(2);
valinFileStatic1.cpp=="
<
getVal1()<
valinFileStatic2.cpp=="
getVal2()<
valinFileStatic1.cpp==1
valinFileStatic2.cpp==2
10-11
Createasimpleclasscontaininganint,aconstructorthatinitializestheintfromitsargument,amemberfunctiontosettheintfromitsargument,andaprint()functionthatprintstheint.Putyourclassinaheaderfile,andincludetheheaderfileintwocppfiles.Inonecppfilemakeaninstanceofyourclass,andintheotherdeclarethatidentifierexternandtestitinsidemain().Remember,you’llhavetolinkthetwoobjectfilesorelsethelinkerwon’tfindtheobject.
10-12
MaketheinstanceoftheobjectinExercise11staticandverifythatitcannotbefoundbythelinkerbecauseofthis.
10-13
Declareafunctioninaheaderfile.Definethefunctioninonecppfileandcallitinsidemain()inasecondcppfile.Compileandverifythatitworks.Nowchangethefunctiondefinitionsothatitisstaticandverifythatthelinkercannotfindit.
10-14
Writeandcompileasimpleprogramthatusestheautoandregisterkeywords.
10-15
ModifyVolatile.cppfromChapter8tomakecomm:
isr()somethingthatcouldactuallyworkasaninterruptserviceroutine.Hint:
aninterruptserviceroutinedoesn’ttakeanyarguments.
10-16
Createaheaderfilecontaininganamespace.Insidethenamespacecreateseveralfunctiondeclarations.Nowcreateasecondheaderfilethatincludesthefirstoneandcontinuesthenamesp
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+编程思想 答案 第十章 其他章节请点击用户名找 thinking in C+ annotated solution guidecharpter 10 编程 思想 第十 其他 章节 点击 用户名
链接地址:https://www.bdocx.com/doc/22095026.html