完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+Word文档下载推荐.docx
- 文档编号:20363587
- 上传时间:2023-01-22
- 格式:DOCX
- 页数:18
- 大小:42.67KB
完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+Word文档下载推荐.docx
《完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《完整word版C++编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+Word文档下载推荐.docx(18页珍藏版)》请在冰豆网上搜索。
<
"
A:
:
A()\n"
;
}
};
classB{
B(){cout<
B:
B()\n"
classC:
publicA{
Bb;
intmain(){
Cc;
/*Output:
A()
B()
*/
///:
~
The“parts”ofaCobjectareautomaticallyconstructed,inheritedsub-objectsfirst,followedbycontainedobjects.
14-4
Createathree-levelhierarchyofclasseswithdefaultconstructors,alongwithdestructors,bothofwhichannouncethemselvestocout.Verifythatforanobjectofthemostderivedtype,allthreeconstructorsanddestructorsareautomaticallycalled.Explaintheorderinwhichthecallsaremade.
HierarchyConstruction.cpp
~A(){cout<
~A()\n"
classB:
~B(){cout<
~B()\n"
publicB{
C(){cout<
C:
C()\n"
~C(){cout<
~C()\n"
C()
~C()
~B()
~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<
void*>
andredefinethepush_back()andoperator[]memberfunctionstoacceptandproducestring*.Whathappensifyoutrytopush_back()avoid*?
StringVector.cpp
//{-msc}VC++onlyfakesreinterpret_cast
vector>
string>
cstddef>
//Forsize_t
classStringVector:
publicvector<
{
voidpush_back(string*s){
vector<
push_back(s);
}
string*&
operator[](size_tn){
returnreinterpret_cast<
string*>
(vector<
operator[](n));
conststring*operator[](size_tn)const{
conststring*>
StringVectorv;
strings1("
live"
),s2("
long"
),s3("
and"
),s4("
prosper"
);
v.push_back(&
s1);
s2);
s3);
s4);
for(size_ti=0;
i<
v.size();
++i)
cout<
*v[i]<
endl;
//void*p=&
s1;
//v.push_back(p);
//error
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.
privatevector<
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.
BusinessTraveler.cpp
classTraveler{
stringstr;
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{
Pager(conststring&
Pager(constPager&
p):
str(p.str){}
Pager&
operator=(constPager&
p){
p)
str=p.str;
classBusinessTraveler:
publicTraveler{
Pagerpager;
BusinessTraveler():
Traveler("
"
),pager("
){}
BusinessTraveler(conststring&
t,conststring&
p)
:
Traveler(t),pager(p){}
BusinessTraveler(constBusinessTraveler&
b)
Traveler(b),pager(b.pager){}
BusinessTraveler&
operator=(constBusinessTraveler&
b){
b){
Traveler:
operator=(b);
//Assignbasepart
pager=b.pager;
//Assignderivedpart
friendostream&
operator<
(ostream&
os,
constBusinessTraveler&
returnos<
{\"
<
b.getString()<
\"
\"
b.pager.getString()<
}"
BusinessTravelerb1("
JoeBusinessMan"
"
Pager1"
b1<
BusinessTravelerb2("
JaneBusinessWoman"
Pager2"
b2<
BusinessTravelerb3;
b3<
BusinessTravelerb4(b1);
b4<
b3=b2;
{"
}*/
ThesolutionisalittleclearerifBusinessTravelerhasaconstructorthattakestwoarguments:
onefortheTraveler’snameandoneforthePagername.Thekeypointofthisexerciseistogettheconstructorandassignmentoperatorcorrectwithinheritance.Bothneedtomakesurethatthebaseclasssub-objectistakencareof(whichissometimeseasytoforget!
).Inconstructorsyouusetheinitializerlist;
inassignmentoperatorsyouexplicitlycallthebaseclassassignmentoperator(sincethebaseclassdataisprivate,youhavenochoice).
14-15
Createaclasswithtwostaticmemberfunctions.Inheritfromthisclassandredefineoneofthememberfunctions.Showthattheotherishiddeninthederivedclass.
StaticBaseMethods.cpp
classBase{
staticvoidf(){
Base:
f()\n"
staticvoidg(){
g()\n"
classDerived:
publicBase{
staticvoidg(int){
Derived:
g(int)\n"
Derived:
f();
g
(1);
//Derived:
g();
//Error:
toofewparameters
f()
g(int)
ThefactthatIintroducedaparameterforg()inDerivedisnotsignificant;
anyfunctionnamedthesameasoneinanybaseclasshidesalloverloadedfunctionsofthesamenameinthebaseclasses(becausederivedclassesconstituteanestedscope).
14-16
Lookupmoreofthememberfunctionsfori
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 完整word版C+编程思想 答案 第十四章 其他章节点击用户名找 thinking in C+ 完整 word C+ 编程 思想 第十四 其他 章节 点击 用户名
链接地址:https://www.bdocx.com/doc/20363587.html