版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2026年德陽市第十六中學校公開招聘10名臨聘工作人員的備考題庫參考答案詳解
- 2026年南通市經濟技術開發(fā)區(qū)教育系統公開招聘幼兒教師中心工作人員的備考題庫及答案詳解1套
- 2026年國機數字科技有限公司招聘備考題庫完整答案詳解
- 2026年和安縣城市發(fā)展投資有限責任公司備考題庫完整答案詳解
- 2026年北京世源希達工程技術有限公司招聘備考題庫及答案詳解參考
- 2026年度寧夏招錄選調生選報備考題庫及1套完整答案詳解
- 2026年崇左市市場監(jiān)督管理局公開招聘所屬事業(yè)單位編外聘用人員備考題庫及一套參考答案詳解
- 2026年北京石晶光電科技股份有限公司招聘備考題庫及完整答案詳解1套
- 2026年萬安第二中心幼兒園招聘啟示備考題庫及1套參考答案詳解
- 2026年宜賓市江安縣交通運輸局招聘工作人員15名備考題庫及完整答案詳解一套
- 課題二教書育人課件
- 半條被子的故事課件
- 人音版七年級音樂下冊(簡譜)第一單元 《☆一二三四歌》教案
- 全國各氣象臺站區(qū)站號及經緯度
- 危險廢物貯存污染控制標準解讀II
- 起重裝卸機械操作工國家職業(yè)技能標準(2023年版)
- 環(huán)球雅思雅思封閉VIP保爭分人班協議合同書
- 中國傳統文化ppt
- 現代漢語語法研究-陸儉明
- 趙玉平管理領導學
- JJF 1129-2005尿液分析儀校準規(guī)范
評論
0/150
提交評論