完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+.docx
- 文档编号:7256808
- 上传时间:2023-01-22
- 格式:DOCX
- 页数:18
- 大小:42.67KB
完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+.docx
《完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+.docx》由会员分享,可在线阅读,更多相关《完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+.docx(18页珍藏版)》请在冰豆网上搜索。
完整word版C++编程思想答案第十四章其他章节点击用户名找thinkinginC+
[ViewingHints][BookHomePage][FreeNewsletter]
[Seminars][SeminarsonCDROM][Consulting]
AnnotatedSolutionGuide
Revision1.0
forThinkinginC++,2ndedition,Volume1
byChuckAllison
©2001MindView,Inc.AllRightsReserved.
[PreviousChapter][TableofContents][NextChapter]
Chapter14
14-1
ModifyCar.cppsothatitalsoinheritsfromaclasscalledVehicle,placingappropriatememberfunctionsinVehicle(thatis,makeupsomememberfunctions).AddanondefaultconstructortoVehicle,whichyoumustcallinsideCar’sconstructor.
14-2
Createtwoclasses,AandB,withdefaultconstructorsthatannouncethemselves.InheritanewclasscalledCfromA,andcreateamemberobjectofBinC,butdonotcreateaconstructorforC.CreateanobjectofclassCandobservetheresults.
14-3
Createtwoclasses,AandB,withdefaultconstructorsthatannouncethemselves.InheritanewclasscalledCfromA,andcreateamemberobjectofBinC,butdonotcreateaconstructorforC.CreateanobjectofclassCandobservetheresults.
Solution:
//:
S14:
DefaultConstruction.cpp
#include
usingnamespacestd;
classA{
public:
A(){cout<<"A:
:
A()\n";}
};
classB{
public:
B(){cout<<"B:
:
B()\n";}
};
classC:
publicA{
Bb;
};
intmain(){
Cc;
}
/*Output:
A:
:
A()
B:
:
B()
*/
///:
~
The“parts”ofaCobjectareautomaticallyconstructed,inheritedsub-objectsfirst,followedbycontainedobjects.
14-4
Createathree-levelhierarchyofclasseswithdefaultconstructors,alongwithdestructors,bothofwhichannouncethemselvestocout.Verifythatforanobjectofthemostderivedtype,allthreeconstructorsanddestructorsareautomaticallycalled.Explaintheorderinwhichthecallsaremade.
Solution:
//:
S14:
HierarchyConstruction.cpp
#include
usingnamespacestd;
classA{
public:
A(){cout<<"A:
:
A()\n";}
~A(){cout<<"A:
:
~A()\n";}
};
classB:
publicA{
public:
B(){cout<<"B:
:
B()\n";}
~B(){cout<<"B:
:
~B()\n";}
};
classC:
publicB{
public:
C(){cout<<"C:
:
C()\n";}
~C(){cout<<"C:
:
~C()\n";}
};
intmain(){
Cc;
}
/*Output:
A:
:
A()
B:
:
B()
C:
:
C()
C:
:
~C()
B:
:
~B()
A:
:
~A()
*/
///:
~
Anobject’s“parts”arealwaysconstructedbeforetheobjectitself.Applyingthisprinciplerecursivelyrequiresthatthesub-objectatthetopofthehierarchymustbecreatedfirst.Destructionisalwaysthereverseorderofconstruction.
(Exercises14-5through14-8arelefttothereader.)
14-5
InCombined.cpp,createaclassDthatinheritsfromBandhasamemberobjectofclassC.Addcodetoshowwhentheconstructorsanddestructorsarebeingcalled.
14-6
ModifyOrder.cpptoaddanotherlevelofinheritanceDerived3withmemberobjectsofclassMember4andMember5.Tracetheoutputoftheprogram.
14-7
InNameHiding.cpp,verifythatinDerived2,Derived3,andDerived4,noneofthebase-classversionsoff()areavailable.
14-8
ModifyNameHiding.cppbyaddingthreeoverloadedfunctionsnamedh()toBase,andshowthatredefiningoneoftheminaderivedclasshidestheothers.
14-9
InheritaclassStringVectorfromvector
Solution:
//:
S14:
StringVector.cpp
//{-msc}VC++onlyfakesreinterpret_cast
#include
#include
#include
#include
usingnamespacestd;
classStringVector:
publicvector
public:
voidpush_back(string*s){
vector
:
push_back(s);
}
string*&operator[](size_tn){
returnreinterpret_cast
(vector
:
operator[](n));
}
conststring*operator[](size_tn)const{
returnreinterpret_cast
(vector
:
operator[](n));
}
};
intmain(){
StringVectorv;
strings1("live"),s2("long"),s3("and"),s4("prosper");
v.push_back(&s1);
v.push_back(&s2);
v.push_back(&s3);
v.push_back(&s4);
for(size_ti=0;i cout<<*v[i]< //void*p=&s1; //v.push_back(p);//error } /*Output: live long and prosper */ ///: ~ Theproblemwiththecommented-outpush_back()aboveisthatthereisnoimplicitconversionfromavoid*toanyothertype,asthereisinC.ThismakesStringVectortype-safe.NotethatIoverloadedbothversionsofoperator[](constandnon-const). Ifyou’vedoneanyamountofreadingonobject-orientedprogramminginC++,youprobablyhavelearnedthatyoushouldneveroverrideanon-virtualfunctionfromapublicly-inheritedclass(seeforexample,ScottMeyers“EffectiveC++”,Item37).Thestandardcontainerssuchasvectorhavenovirtualfunctionsatall,sotheremustbeabetterwaytodefineStringVector.TheBetterWayistouseprivateinheritance,andprovideaccesstotheinheritedfunctionsasthefollowingversionillustrates. classStringVector: privatevector public: voidpush_back(string*s){ vector : push_back(s); } string*&operator[](size_tn){ returnreinterpret_cast (vector : operator[](n)); } conststring*operator[](size_tn)const{ returnreinterpret_cast (vector : operator[](n)); } usingvector : size; }; Privateinheritancecombinedwithtemplatesmakesbuildingsuchtype-safecontainersfairlysimple.(SeeChapter16andVolume2). (Exercises14-10through14-13arelefttothereader.) 14-10 Writeaclasscontainingalongandusethepsuedo-constructorcallsyntaxintheconstructortoinitializethelong. 14-11 CreateaclasscalledAsteroid.UseinheritancetospecializethePStashclassinChapter13(PStash.h&PStash.cpp)sothatitacceptsandreturnsAsteroidpointers.AlsomodifyPStashTest.cpptotestyourclasses.ChangetheclasssoPStashisamemberobject. 14-12 RepeatExercise11withavectorinsteadofaPStash. 14-13 InSynthesizedFunctions.cpp,modifyChesstogiveitadefaultconstructor,copy-constructor,andassignmentoperator.Demonstratethatyou’vewrittenthesecorrectly. 14-14 CreatetwoclassescalledTravelerandPagerwithoutdefaultconstructors,butwithconstructorsthattakeanargumentoftypestring,whichtheysimplycopytoaninternalstringvariable.Foreachclass,writethecorrectcopy-constructorandassignmentoperator.NowinheritaclassBusinessTravelerfromTravelerandgiveitamemberobjectoftypePager.Writethecorrectdefaultconstructor,aconstructorthattakesastringargument,acopy-constructor,andanassignmentoperator. Solution: //: S14: BusinessTraveler.cpp #include #include usingnamespacestd; classTraveler{ stringstr; public: Traveler(conststring&s): str(s){} Traveler(constTraveler&t): str(t.str){} Traveler&operator=(constTraveler&t){ if(this! =&t) str=t.str; return*this; } stringgetString()const{ returnstr; } }; classPager{ stringstr; public: Pager(conststring&s): str(s){} Pager(constPager&p): str(p.str){} Pager&operator=(constPager&p){ if(this! =&p) str=p.str; return*this; } stringgetString()const{ returnstr; } }; classBusinessTraveler: publicTraveler{ Pagerpager; public: BusinessTraveler(): Traveler(""),pager(""){} BusinessTraveler(conststring&t,conststring&p) : Traveler(t),pager(p){} BusinessTraveler(constBusinessTraveler&b) : Traveler(b),pager(b.pager){} BusinessTraveler&operator=(constBusinessTraveler&b){ if(this! =&b){ Traveler: : operator=(b);//Assignbasepart pager=b.pager;//Assignderivedpart } return*this; } friendostream&operator<<(ostream&os, constBusinessTraveler&b){ returnos<<"{\""< < } }; intmain(){ BusinessTravelerb1("JoeBusinessMan","Pager1"); cout< BusinessTravelerb2("JaneBusinessWoman","Pager2"); cout< BusinessTravelerb3; cout< BusinessTravelerb4(b1); cout< b3=b2; cout< } /*Output: {"JoeBusinessMan","Pager1"} {"JaneBusinessWoman","Pager2"} {"",""} {"JoeBusinessMan","Pager1"} {"JaneBusinessWoman","Pager2"}*/ ///: ~ ThesolutionisalittleclearerifBusinessTravelerhasaconstructorthattakestwoarguments: onefortheTraveler’snameandoneforthePagername.Thekeypointofthisexerciseistogettheconstructorandassignmentoperatorcorrectwithinheritance.Bothneedtomakesurethatthebaseclasssub-objectistakencareof(whichissometimeseasytoforget! ).Inconstructorsyouusetheinitializerlist;inassignmentoperatorsyouexplicitlycallthebaseclassassignmentoperator(sincethebaseclassdataisprivate,youhavenochoice). 14-15 Createaclasswithtwostaticmemberfunctions.Inheritfromthisclassandredefineoneofthememberfunctions.Showthattheotherishiddeninthederivedclass. Solution: //: S14: StaticBaseMethods.cpp #include usingnamespacestd; classBase{ public: staticvoidf(){ cout<<"Base: : f()\n"; } staticvoidg(){ cout<<"Base: : g()\n"; } }; classDerived: publicBase{ public: staticvoidg(int){ cout<<"Derived: : g(int)\n"; } }; intmain(){ Derived: : f(); Derived: : g (1); //Derived: : g();//Error: toofewparameters } /*Output: Base: : f() Derived: : g(int) */ ///: ~ ThefactthatIintroducedaparameterforg()inDerivedisnotsignificant;anyfunctionnamedthesameasoneinanybaseclasshidesalloverloadedfunctionsofthesamenameinthebaseclasses(becausederivedclassesconstituteanestedscope). 14-16 Lookupmoreofthememberfunctionsfori
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 完整word版C+编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+ 完整 word C+ 编程 思想 第十四 其他 章节 点击 用户名
![提示](https://static.bdocx.com/images/bang_tan.gif)
链接地址:https://www.bdocx.com/doc/7256808.html