C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7.docx
- 文档编号:5268129
- 上传时间:2022-12-14
- 格式:DOCX
- 页数:8
- 大小:38.31KB
C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7.docx
《C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7.docx》由会员分享,可在线阅读,更多相关《C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7.docx(8页珍藏版)》请在冰豆网上搜索。
C++编程思想答案第七章其他章节请点击用户名找thinkinginC++annotatedsolutionguidecharpter7
[ViewingHints][BookHomePage][FreeNewsletter]
[Seminars][SeminarsonCDROM][Consulting]
AnnotatedSolutionGuide
Revision1.0
forThinkinginC++,2ndedition,Volume1
byChuckAllison
©2001MindView,Inc.AllRightsReserved.
[PreviousChapter][TableofContents][NextChapter]
Chapter7
7-1
CreateaTextclassthatcontainsastringobjecttoholdthetextofafile.Giveittwoconstructors:
adefaultconstructorandaconstructorthattakesastringargumentthatisthenameofthefiletoopen.Whenthesecondconstructorisused,openthefileandreadthecontentsintothestringmemberobject.Addamemberfunctioncontents()toreturnthestringso(forexample)itcanbeprinted.Inmain(),openafileusingTextandprintthecontents.
Solution:
//:
S07:
Text.cpp
#include
#include
#include
usingnamespacestd;
classText{
stringtext;
public:
Text(){}
Text(conststring&fname){
ifstreamifs(fname.c_str());
stringline;
while(getline(ifs,line))
text+=line+'\n';
}
stringcontents(){
returntext;
}
};
intmain(intargc,char*argv[]){
if(argc>1)
{
Textt1;
Textt2(argv[1]);
cout<<"t1:
\n"< cout<<"t2: \n"< } } ///: ~ WhencreatingaTextobject,thecompilerguaranteesthatthetextdatamemberhasitsdefaultconstructor(string: : string())executedbeforeeitherTextconstructorruns,hencethedefaultTextconstructorjustbuildsanemptystring.Thisprogramprintsanemptystringfort1followedbythecontentsofthefilenamedinthefirstcommand-lineargument.Notetheuseofstring: : c_str()inthesecondconstructor.That’sbecausetheifstreamconstructortakesachar*argument,notastring. 7-2 CreateaMessageclasswithaconstructorthattakesasinglestringwithadefaultvalue.Createaprivatememberstring,andintheconstructorsimplyassigntheargumentstringtoyourinternalstring.Createtwooverloadedmemberfunctionscalledprint(): onethattakesnoargumentsandsimplyprintsthemessagestoredintheobject,andonethattakesastringargument,whichitprintsinadditiontotheinternalmessage.Doesitmakesensetousethisapproachinsteadoftheoneusedfortheconstructor? Solution: //: S07: Message.cpp #include #include usingnamespacestd; classMessage{ stringmsg; public: Message(conststring&s="MSG"): msg(s){} voidprint(){ cout< } voidprint(conststring&suffix){ cout< } }; intmain(){ Messagem1; Messagem2("Error"); m1.print(); m2.print(); m1.print("hello"); m2.print("goodbye"); } /*Output: MSG Error MSGhello Errorgoodbye */ ///: ~ It’susuallymoreflexibletoallowoptionalargumentsinthecalltoprint,sincethetextofamessageisfixedwhenitiscreated.Acommontechniqueallowsanoptionalprefixformessages,asthefollowingexampleillustrates. //: S07: MessageWithPrefix.cpp #include #include usingnamespacestd; classMessage{ stringmsg; public: Message(conststring&s): msg(s){} voidprint(){ cout< } voidprint(conststring&prefix){ cout< "< } }; intmain(){ Messagem("Thisisamessage"); m.print(); m.print("Attention"); } /*Output: Thisisamessage Attention: Thisisamessage */ ///: ~ 7-3 Determinehowtogenerateassemblyoutputwithyourcompiler,andrunexperimentstodeducethename-decorationscheme. (Lefttothereader) 7-4 Createaclassthatcontainsfourmemberfunctions,with0,1,2,and3intarguments,respectively.Createamain()thatmakesanobjectofyourclassandcallseachofthememberfunctions.Nowmodifytheclasssoithasinsteadasinglememberfunctionwithalltheargumentsdefaulted.Doesthischangeyourmain()? Solution: Here’sthefirstversion: //: S07: ManyArgs.cpp #include usingnamespacestd; classManyArgs{ public: voidf(){ cout<<"{}\n"; } voidf(inti){ cout<<"{"< } voidf(inti,intj){ cout<<"{"< } voidf(inti,intj,intk){ cout<<"{"< } }; intmain(){ ManyArgsa; a.f(); a.f (1); a.f(1,2); a.f(1,2,3); } /*Output: {} {1} {1,2} {1,2,3} */ ///: ~ Nowcomparetheoutputabovetothatfromthisdefault-argumentversion: //: S07: DefaultArgs.cpp #include usingnamespacestd; classDefaultArgs{ public: voidf(inti=0,intj=0,intk=0){ cout<<"{"< } }; intmain(){ DefaultArgsa; a.f(); a.f (1); a.f(1,2); a.f(1,2,3); } /*Output: {0,0,0} {1,0,0} {1,2,0} {1,2,3} */ ///: ~ Althoughit’struethattheoperationsinmain()didnotchange,therespectiveoutputssuggestwheneachfeatureisappropriate.Usedefaultargumentswhentheretrulyisadefaultvalue(likezeroabove).Whenyouwantnovalueatallincertaininstances,thenthefunctionsaredifferentenoughthatyouneedtheoverloads. 7-5 Createafunctionwithtwoargumentsandcallitfrommain().Nowmakeoneoftheargumentsa“placeholder”(noidentifier)andseeifyourcallinmain()changes. Solution: //: S07: NamelessArg.cpp #include usingnamespacestd; voidtwoArgs(inti,floatx){ cout<<"twoArgs("< } voidplaceHolder(inti,float){ cout<<"twoArgs("< } intmain(){ twoArgs(1,2); placeHolder(1,2); } /*Output: twoArgs(1,2) twoArgs(1,) */ ///: ~ Placeholdersareusefulinthoserareoccasions(ofteninmaintainingcode)whenyouneeddifferentversionsofafunction,butonlythetype,notthevalue,ofthedifferentiatingparameterisimportant. (Exercises6–10lefttothereader) 7-6 ModifyStash3.handStash3.cpptousedefaultargumentsintheconstructor.TesttheconstructorbymakingtwodifferentversionsofaStashobject. (Lefttothereader) 7-7 CreateanewversionoftheStackclass(fromChapter6)thatcontainsthedefaultconstructorasbefore,andasecondconstructorthattakesasitsargumentsanarrayofpointerstoobjectsandthesizeofthatarray.ThisconstructorshouldmovethroughthearrayandpusheachpointerontotheStack.Testyourclasswithanarrayofstring. (Lefttothereader) 7-8 ModifySuperVarsothatthereare#ifdefsaroundallthevartypecodeasdescribedinthesectiononenum.Makevartypearegularandpublicenumeration(withnoinstance)andmodifyprint()sothatitrequiresavartypeargumenttotellitwhattodo. (Lefttothereader) 7-9 ImplementMem2.handmakesurethatthemodifiedclassstillworkswithMemTest.cpp. (Lefttothereader) 7-10 UseclassMemtoimplementStash.Notethatbecausetheimplementationisprivateandthushiddenfromtheclientprogrammer,thetestcodedoesnotneedtobemodified. InclassMem,addaboolmoved()memberfunctionthattakestheresultofacalltopointer()andtellsyouwhetherthepointerhasmoved(duetoreallocation).Writeamain()thattestsyourmoved()memberfunction.Doesitmakemoresensetousesomethinglikemoved()ortosimplycallpointer()everytimeyouneedtoaccessthememoryinMem? (Lefttothereader) [PreviousChapter][TableofContents][NextChapter] LastUpdate: 06/27/2002
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+编程思想 答案 第七章 其他章节请点击用户名找 thinking in C+ annotated solution guidecharpter 编程 思想 第七 其他 章节 点击 用户名
链接地址:https://www.bdocx.com/doc/5268129.html