C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7Word格式文档下载.docx
《C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7Word格式文档下载.docx(8页珍藏版)》请在冰点文库上搜索。
![C++编程思想 答案 第七章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 7Word格式文档下载.docx](https://file1.bingdoc.com/fileroot1/2023-5/11/6935e12c-6096-40eb-9bfa-93b63c6d2a6d/6935e12c-6096-40eb-9bfa-93b63c6d2a6d1.gif)
Text.cpp
#include<
iostream>
fstream>
string>
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"
<
t1.contents()<
endl;
t2:
t2.contents()<
}
///:
~
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?
Message.cpp
classMessage{
stringmsg;
Message(conststring&
s="
MSG"
):
msg(s){}
voidprint(){
msg<
voidprint(conststring&
suffix){
'
suffix<
intmain(){
Messagem1;
Messagem2("
Error"
);
m1.print();
m2.print();
m1.print("
hello"
m2.print("
goodbye"
/*Output:
MSG
Error
MSGhello
Errorgoodbye
*/
It’susuallymoreflexibletoallowoptionalargumentsinthecalltoprint,sincethetextofamessageisfixedwhenitiscreated.Acommontechniqueallowsanoptionalprefixformessages,asthefollowingexampleillustrates.
MessageWithPrefix.cpp
s):
prefix){
prefix<
Messagem("
Thisisamessage"
m.print();
m.print("
Attention"
Thisisamessage
Attention:
Thisisamessage
7-3
Determinehowtogenerateassemblyoutputwithyourcompiler,andrunexperimentstodeducethename-decorationscheme.
(Lefttothereader)
7-4
Createaclassthatcontainsfourmemberfunctions,with0,1,2,and3intarguments,respectively.Createamain()thatmakesanobjectofyourclassandcallseachofthememberfunctions.Nowmodifytheclasssoithasinsteadasinglememberfunctionwithalltheargumentsdefaulted.Doesthischangeyourmain()?
Here’sthefirstversion:
ManyArgs.cpp
classManyArgs{
voidf(){
{}\n"
voidf(inti){
{"
i<
}\n"
voidf(inti,intj){
"
j<
voidf(inti,intj,intk){
k<
ManyArgsa;
a.f();
a.f
(1);
a.f(1,2);
a.f(1,2,3);
{}
{1}
{1,2}
{1,2,3}
Nowcomparetheoutputabovetothatfromthisdefault-argumentversion:
DefaultArgs.cpp
classDefaultArgs{
voidf(inti=0,intj=0,intk=0){
DefaultArgsa;
{0,0,0}
{1,0,0}
{1,2,0}
Althoughit’struethattheoperationsinmain()didnotchange,therespectiveoutputssuggestwheneachfeatureisappropriate.Usedefaultargumentswhentheretrulyisadefaultvalue(likezeroabove).Whenyouwantnovalueatallincertaininstances,thenthefunctionsaredifferentenoughthatyouneedtheoverloads.
7-5
Createafunctionwithtwoargumentsandcallitfrommain().Nowmakeoneoftheargumentsa“placeholder”(noidentifier)andseeifyourcallinmain()changes.
NamelessArg.cpp
voidtwoArgs(inti,floatx){
twoArgs("
x<
)\n"
voidplaceHolder(inti,float){
)\n"
twoArgs(1,2);
placeHolder(1,2);
twoArgs(1,2)
twoArgs(1,)
Placeholdersareusefulinthoserareoccasions(ofteninmaintainingcode)whenyouneeddifferentversionsofafunction,butonlythetype,notthevalue,ofthedifferentiatingparameterisimportant.
(Exercises6–10lefttothereader)
7-6
ModifyStash3.handStash3.cpptousedefaultargumentsintheconstructor.TesttheconstructorbymakingtwodifferentversionsofaStashobject.
7-7
CreateanewversionoftheStackclass(fromChapter6)thatcontainsthedefaultconstructorasbefore,andasecondconstructorthattakesasitsargumentsanarrayofpointerstoobjectsandthesizeofthatarray.ThisconstructorshouldmovethroughthearrayandpusheachpointerontotheStack.Testyourclasswithanarrayofstring.
7-8
ModifySuperVarsothatthereare#ifdefsaroundallthevartypecodeasdescribedinthesectiononenum.Makevartypearegularandpublicenumeration(withnoinstance)andmodifyprint()sothatitrequiresavartypeargumenttotellitwhattodo.
7-9
ImplementMem2.handmakesurethatthemodifiedclassstillworkswithMemTest.cpp.
7-10
UseclassMemtoimplementStash.Notethatbecausetheimplementationisprivateandthushiddenfromtheclientprogrammer,thetestcodedoesnotneedtobemodified.
InclassMem,addaboolmoved()memberfunctionthattakestheresultofacalltopointer()andtellsyouwhetherthepointerhasmoved(duetoreallocation).Writeamain()thattestsyourmoved()memberfunction.Doesitmakemoresensetousesomethinglikemoved()ortosimplycallpointer()everytimeyouneedtoaccessthememoryinMem?
LastUpdate:
06/27/2002