C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 5Word文档格式.docx
《C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 5Word文档格式.docx》由会员分享,可在线阅读,更多相关《C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guidecharpter 5Word文档格式.docx(17页珍藏版)》请在冰点文库上搜索。
//:
S05:
PointToMeAndYou.cpp
#include<
iostream>
usingnamespacestd;
classYou;
//Forwarddeclaration
classMe{
public:
voidProcessYou(You*p){
cout<
<
"
ProcessingYouat"
<
p<
endl;
}
};
classYou{
voidProcessMe(Me*p){
ProcessingMeat"
intmain(){
Meme;
Youyou;
me.ProcessYou(&
you);
you.ProcessMe(&
me);
}
/*Output:
ProcessingYouat0065FDF4
ProcessingMeat0065FDFC
*/
///:
~
Whentwoclassesrefertoeachother,itisnecessarytoforward-declareatleastoneofthem,asIdidabove.Youmustonlyusepointers,ofcourse,oryou’lltrulyfindyourselfinachicken-and-eggfix.FYI:
whenclasseshavearelationship,forexample,andEmployee“has-a”Manager,itiscommontoreflectthisrelationshipbyactuallystoringapointertotheManagerobjectasamemberintheEmployeeobject,soyoudon’thavetoexplicitlypasspointersasargumentstomemberfunctionslikeIdidhere.
5-5
Createthreeclasses.Thefirstclasscontainsprivatedata,andgrantsfriendshiptotheentiresecondclassandtoamemberfunctionofthethirdclass.Inmain(),demonstratethatalloftheseworkcorrectly.
MyFriends.cpp
classHasStuff;
//MustprecedeGoodFrienddefinition
classGoodFriend{//MustprecedeHasStuffdefinition
voidhasAccess(HasStuff*p);
voidhasNoAccess(HasStuff*p){
Cannotaccess"
classHasStuff{
private:
intx;
friendclassBestFriend;
friendvoidGoodFriend:
:
hasAccess(HasStuff*);
//MustfollowHasStuffdefinition:
voidGoodFriend:
hasAccess(HasStuff*p){
FromGoodFriend:
hasAccess:
p->
x<
//AllmethodsofBestFriendhaveaccesstoHasStuff:
x
//ThismustalsofollowtheHasStuffdefinition:
classBestFriend{
voidinitFriend(HasStuff*p){
x=5;
voidqueryFriend(HasStuff*p){
FromBestFriend:
HasStuffh;
BestFriendb;
b.initFriend(&
h);
b.queryFriend(&
GoodFriendg;
g.hasAccess(&
g.hasNoAccess(&
5
Cannotaccess0065FE00
Thisisanotherexerciseinforwarddeclarations.ThedefinitionofGoodFriendrequirestheexistenceofclassHasStuff,butIcannotincludetheimplementationofGoodFriend:
hasAccess()insitu,becauseitusesthefactthatHasStuffcontainsanintegernamedx(likewisefortheentireclassBestFriend).Also,ifyoutriedtoaccessHasStuff:
xinGoodFriend:
hasNoAccess()youwouldgetacompilererror.Thestatement“friendclassBestFriend”insideofHasStuffissimultaneouslyaforwarddeclarationandafrienddeclaration,otherwiseIwouldhavehadtoforward-declareBestFriendbeforethedefinitionofHasStuff(butI’mlazy).
5-6
CreateaHenclass.Insidethis,nestaNestclass.InsideNest,placeanEggclass.Eachclassshouldhaveadisplay()memberfunction.Inmain(),createaninstanceofeachclassandcallthedisplay()functionforeachone.
NestedFriends.cpp
classHen{
voiddisplay(){
Hen:
display\n"
;
classNest{
public:
Nest:
classEgg{
Egg:
};
Henh;
Hen:
Nestn;
Egge;
h.display();
n.display();
e.display();
display
NestandEggarejustlikenormalclassesexcepttheyresideinthescopeofotherclassesinsteadoftheglobalscope,whichexplainstheneedfortheexplicitqualificationviathescoperesolutionoperator.Also,HenhasnoaccessrightstoanyprivatemembersofNestorEgg,nordoesNesthaveanyrightstoEgg’sprivatemembers(iftherewereany–seethenextexercise).
5-7
ModifyExercise6sothatNestandEggeachcontainprivatedata.Grantfriendshiptoallowtheenclosingclassesaccesstothisprivatedata.
friendclassHen;
inty;
friendclassNest;
display:
y<
voidinitEgg(Egg*e){
e->
y=2;
x<
voidinitNest(Nest*n){
n->
x=1;
h.initNest(&
n);
n.initEgg(&
e);
1
2
InthisexampleIhadtomovetheimplementationofHen:
display()pastthenestedclassEgg,becauseitaccessmembersofEgg.Thesamereasoningappliestotheinit-functionsabove.
5-8
Createaclasswithdatamembersdistributedamongnumerouspublic,private,andprotectedsections.AddamemberfunctionshowMap()thatprintsthenamesofeachofthesedatamembersandtheiraddresses.Ifpossible,compileandrunthisprogramonmorethanonecompilerand/orcomputerand/oroperatingsystemtoseeiftherearelayoutdifferencesintheobject.
Here’sasamplefortwoparticularcompilers:
MapMembers.cpp
classMapped{
protected:
intz;
voidshowMap(){
xisat"
&
yisat"
y<
zisat"
z<
Mappedm;
m.showMap();
//CompilerA:
xisat0065FDF8
yisat0065FDFC
zisat0065FE00
//CompilerB:
xisat0064FDEC
yisat0064FDF0
zisat0064FDF4
5-9
CopytheimplementationandtestfilesforStashinChapter4sothatyoucancompileandtestStash.hinthischapter.
5-10
PlaceobjectsoftheHenclassfromExercise6inaStash.Fetchthemoutandprintthem(ifyouhavenotalreadydoneso,youwillneedtoaddHen:
print()).
5-11
CopytheimplementationandtestfilesforStackinChapter4sothatyoucancompileandtestStack2.hinthischapter.
5-12
PlaceobjectsoftheHenclassfromExercise6inaStack.Fetchthemoutandprintthem(ifyouhavenotalreadydoneso,youwillneedtoaddHen:
5-13
ModifyCheshireinHandle.cpp,andverifythatyourprojectmanagerrecompilesandrelinksonlythisfile,butdoesn’trecompileUseHandle.cpp.
5-14
CreateaStackOfIntclass(astackthatholdsints)usingthe“Cheshirecat”techniquethathidesthelow-leveldatastructureyouusetostoretheelementsinaclasscalledStackImp.ImplementtwoversionsofStackImp:
onethatusesafixed-lengtharrayofint,andonethatusesavector<
int>
.Haveapresetmaximumsizeforthestacksoyoudon’thavetoworryaboutexpandingthearrayinthefirstversion.NotethattheStackOfInt.hclassdoesn’thavetochangewithStackImp.
Here’stheStackOfIntclass:
StackOfInt.h
cstddef>
//forsize_t
climits>
//forINT_MIN
//VC++doesn’tputsize_tinstd:
#ifndef_MSC_VER
usingstd:
size_t;
#endif
structStackImp;
//Incompletetypedeclaration
structStackOfInt{
enum{STKERROR=INT_MIN};
voidinit();
voidcleanup();
intpush(int);
intpop();
inttop();
size_tsize();
StackImp*pImpl;
//The“smile”
TodoCheshireCat,IjustdeclaretheStackImpclass(thismakesitan“incomplete”type),anddeclareapointertoitasamemberofStackOfInt.TheimplementationsofStackOfInt’smemberfunctionswillusetheinternalsofStackImpviapImpl,soIhavetodefinethemethodbodiesinaseparate.cppfile(otherwisewe’renothidinganything!
).Here’sthe.cppfileforthearrayversion:
StackOfInt1.cpp{O}
//Usesanarraytoi