C++編程思想 答案 第十四章 其他章節(jié)點擊用戶名找 thinking in C++ annotated solution guide(charpter 14)_第1頁
C++編程思想 答案 第十四章 其他章節(jié)點擊用戶名找 thinking in C++ annotated solution guide(charpter 14)_第2頁
C++編程思想 答案 第十四章 其他章節(jié)點擊用戶名找 thinking in C++ annotated solution guide(charpter 14)_第3頁
C++編程思想 答案 第十四章 其他章節(jié)點擊用戶名找 thinking in C++ annotated solution guide(charpter 14)_第4頁
C++編程思想 答案 第十四章 其他章節(jié)點擊用戶名找 thinking in C++ annotated solution guide(charpter 14)_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

C++編程思想答案第十四章其他章節(jié)點擊用戶名找thinkinginC++annotatedsolutionguide(charpter14)C++編程思想答案第十四章其他章節(jié)點擊用戶名找thinkinginC++annotatedsolutionguide(charpter14)C++編程思想答案第十四章其他章節(jié)點擊用戶名找thinkinginC++annotatedsolutionguide(charpter14)C++編程思想答案第十四章其他章節(jié)點擊用戶名找thinkinginC++annotatedsolutionguide(charpter14)編制僅供參考審核批準生效日期地址:電話:傳真:郵編:[ViewingHints][BookHomePage][FreeNewsletter]

[Seminars][SeminarsonCDROM][Consulting]AnnotatedSolutionGuideRevisionforThinkinginC++,2ndedition,Volume1byChuckAllison?2001MindView,Inc.AllRightsReserved.[PreviousChapter][TableofContents][NextChapter]Chapter1414-1ModifysothatitalsoinheritsfromaclasscalledVehicle,placingappropriatememberfunctionsinVehicle(thatis,makeupsomememberfunctions).AddanondefaultconstructortoVehicle,whichyoumustcallinsideCar’sconstructor.14-2Createtwoclasses,AandB,withdefaultconstructorsthatannouncethemselves.InheritanewclasscalledCfromA,andcreateamemberobjectofBinC,butdonotcreateaconstructorforC.CreateanobjectofclassCandobservetheresults.14-3Createtwoclasses,AandB,withdefaultconstructorsthatannouncethemselves.InheritanewclasscalledCfromA,andcreateamemberobjectofBinC,butdonotcreateaconstructorforC.CreateanobjectofclassCandobservetheresults.Solution:14-4Createathree-levelhierarchyofclasseswithdefaultconstructors,alongwithdestructors,bothofwhichannouncethemselvestocout.Verifythatforanobjectofthemostderivedtype,allthreeconstructorsanddestructorsareautomaticallycalled.Explaintheorderinwhichthecallsaremade.Solution:Applyingthisprinciplerecursivelyrequiresthatthesub-objectatthetopofthehierarchymustbecreatedfirst.Destructionisalwaysthereverseorderofconstruction.(Exercises14-5through14-8arelefttothereader.)14-5In,createaclassDthatinheritsfromBandhasamemberobjectofclassC.Addcodetoshowwhentheconstructorsanddestructorsarebeingcalled.14-6ModifytoaddanotherlevelofinheritanceDerived3withmemberobjectsofclassMember4andMember5.Tracetheoutputoftheprogram.14-7In,verifythatinDerived2,Derived3,andDerived4,noneofthebase-classversionsoff()areavailable.14-8Modifybyaddingthreeoverloadedfunctionsnamedh()toBase,andshowthatredefiningoneoftheminaderivedclasshidestheothers.14-9InheritaclassStringVectorfromvector<void*>andredefinethepush_back()andoperator[]memberfunctionstoacceptandproducestring*.Whathappensifyoutrytopush_back()avoid*

Solution:ThismakesStringVectortype-safe.NotethatIoverloadedbothversionsofoperator[](constandnon-const).Ifyou’vedoneanyamountofreadingonobject-orientedprogramminginC++,youprobablyhavelearnedthatyoushouldneveroverrideanon-virtualfunctionfromapublicly-inheritedclass(seeforexample,ScottMeyers“EffectiveC++”,Item37).Thestandardcontainerssuchasvectorhavenovirtualfunctionsatall,sotheremustbeabetterwaytodefineStringVector.TheBetterWayistouseprivateinheritance,andprovideaccesstotheinheritedfunctionsasthefollowingversionillustrates.classStringVector:privatevector<void*>{public:voidpush_back(string*s){vector<void*>::push_back(s);}string*&operator[](size_tn){returnreinterpret_cast<string*>(vector<void*>::operator[](n));}conststring*operator[](size_tn)const{returnreinterpret_cast<conststring*>(vector<void*>::operator[](n));}usingvector<void*>::size;};Privateinheritancecombinedwithtemplatesmakesbuildingsuchtype-safecontainersfairlysimple.(SeeChapter16andVolume2).(Exercises14-10through14-13arelefttothereader.)14-10Writeaclasscontainingalongandusethepsuedo-constructorcallsyntaxintheconstructortoinitializethelong.14-11CreateaclasscalledAsteroid.UseinheritancetospecializethePStashclassinChapter13&sothatitacceptsandreturnsAsteroidpointers.Alsomodifytotestyourclasses.ChangetheclasssoPStashisamemberobject.14-12RepeatExercise11withavectorinsteadofaPStash.14-13In,modifyChesstogiveitadefaultconstructor,copy-constructor,andassignmentoperator.Demonstratethatyou’vewrittenthesecorrectly.14-14CreatetwoclassescalledTravelerandPagerwithoutdefaultconstructors,butwithconstructorsthattakeanargumentoftypestring,whichtheysimplycopytoaninternalstringvariable.Foreachclass,writethecorrectcopy-constructorandassignmentoperator.NowinheritaclassBusinessTravelerfromTravelerandgiveitamemberobjectoftypePager.Writethecorrectdefaultconstructor,aconstructorthattakesastringargument,acopy-constructor,andanassignmentoperator.Solution:Thekeypointofthisexerciseistogettheconstructorandassignmentoperatorcorrectwithinheritance.Bothneedtomakesurethatthebaseclasssub-objectistakencareof(whichissometimeseasytoforget!).Inconstructorsyouusetheinitializerlist;inassignmentoperatorsyouexplicitlycallthebaseclassassignmentoperator(sincethebaseclassdataisprivate,youhavenochoice).14-15Createaclasswithtwostaticmemberfunctions.Inheritfromthisclassandredefineoneofthememberfunctions.Showthattheotherishiddeninthederivedclass.Solution:14-16Lookupmoreofthememberfunctionsforifstream.In,trythemoutonthefileobject.(Lefttothereader)14-17Useprivateandprotectedinheritancetocreatetwonewclassesfromabaseclass.Thenattempttoupcastobjectsofthederivedclasstothebaseclass.Explainwhathappens.Solution:Thesetypesofinheritanceareusedforimplementationonly,therefore,clientsthatonlyhavethepublicinterfaceavailablehavenosuchaccess.14-18In,addamemberfunctioninDerivedthatcallstheprotectedBasememberread().(Lefttothereader.)14-19ChangesothatDerivedisusingprotectedinheritance.Seeifyoucancallvalue()foraDerivedobject.(Lefttothereader.)14-20CreateaclasscalledSpaceShipwithafly()method.InheritShuttlefromSpaceShipandaddaland()method.CreateanewShuttle,upcastbypointerorreferencetoaSpaceShip,andtrytocalltheland()method.Explaintheresults.Solution:ThevariableshipisaSpaceShip,whichdoesnothavealand()method.IfSpaceShiphadalandmethod,therewouldstillbeaproblem:SpaceShip::land()wouldbecalledinsteadofShuttle::land()(rarelytherightthingtodo!).Thismysteryissolvedinthenextchapter(readaboutvirtualfunctions).(Exercises14-21through14-25arelefttothereader.)14-21Modifytoaddaprepare()methodtoInstrument.Callprepare()insidetune().14-22Modifysothatplay()printsamessagetocout,andWindredefinesplay()toprintadifferentmessagetocout.Runtheprogramandexplainwhyyouprobablywouldn’twantthisbehavior.Nowputthevirtualkeyword(whichyouwilllearnaboutinChapter15)infrontoftheplay()declarationinInstrumentandobservethechangeinthebehavior.14-23In,inheritanewclassfromChildandgiveitaMemberm.Writeaproperconstructor,copy-constructor,operator=,andoperator<<forostreams,andtesttheclassinmain().14-24Taketheexampleandmodifyitbyaddingyourowncopy-constructortoChildwithoutcallingthebase-classcopy-constructorandseewhathappens.Fixtheproblembymakingaproperexplicitcalltothebase-classcopyconstructorintheconstructor-initializerlistoftheChildcopy-constructor.14-25Modifytouseavector<string>insteadofaStack.14-26CreateaclassRockwithadefaultconstructor,acopy-constructor,anassignmentoperator,andadestructor,allofwhichannouncetocoutthatthey’vebeencalled.Inmain(),createavector<Rock>(thatis,holdRockobjectsbyvalue)andaddsomeRocks.Runtheprogramandexplaintheoutputyouget.NotewhetherthedestructorsarecalledfortheRockobjectsinthevector.Nowrepeattheexercisewithavector<Rock*>.Isitpossibletocreateavector<Rock&>

Solution:EvenbyPtrstorescopies;they’rejustcopiesofthepointersyousenttopush_back().Asyoucanalsosee,thedestructorofbyValueensuresthatallitselements(copies)aredestroyed.(Again,sodoesbyPtr;pointersjustdon’thavedestructors,soyouseenotraceoutput).Itmakesnosensetohaveavectorofreferences,sincevectorsstorecopies.Ifyoustoreheappointersinacontainer,youareresponsibletodeletethem.14-27Thisexercisecreatesthedesignpatterncalledproxy.StartwithabaseclassSubjectandgiveitthreefunctions:f(),g(),andh().NowinheritaclassProxyandtwoclassesImplementation1andImplementation2fromSubject.ProxyshouldcontainapointertoaSubject,andallthememberfunctionsforProxyshouldjustturnaroundandmakethesamecallsthroughtheSubjectpointer.TheProxyconstructortakesapointertoaSubjectthatisinstalledintheProxy(usuallybytheconstructor).Inmain(),createtwodifferentProxyobjectsthatusethetwodifferentimplementations.NowmodifyProxysothatyoucandynamicallychangeimplementations.Solution:Thisisthewell-knownProxypatternfromtheGangofFour(see"DesignPatterns",Gammaetal,Prentice-Hal

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論