ch08.docx
- 文档编号:27535971
- 上传时间:2023-07-02
- 格式:DOCX
- 页数:15
- 大小:18.65KB
ch08.docx
《ch08.docx》由会员分享,可在线阅读,更多相关《ch08.docx(15页珍藏版)》请在冰豆网上搜索。
ch08
Chapter8Friends,OverloadedOperators,andArraysinClasses
AnswerstoSelf-TestExercises
1.boolbefore(DayOfYeardate1,DayOfYeardate2)
{
return((date1.get_month() ||(date1.get_month()==date2.get_month() } ThepreviousBooleanexpressionsaysthatdate1isbeforedate2,providedthemonthofdate1isbeforethemonthofdate2orthatthemonthsarethesameandthedayofdate1isbeforethedayofdate2. 2.Afriendfunctionandamemberfunctionarealikeinthattheybothcanuseanymemberoftheclass(eitherpublicorprivate)intheirfunctiondefinition.However,afriendfunctionisdefinedandusedjustlikeanordinaryfunction;thedotoperatorisnotusedwhenyoucallafriendfunction,andnotypequalifierisusedwhenyoudefineafriendfunction.Amemberfunction,ontheotherhand,iscalledusinganobjectnameandthedotoperator.Also,amemberfunctiondefinitionincludesatypequalifierconsistingoftheclassnameandthescoperesolutionoperator: : . 3.ThemodifieddefinitionoftheclassDayOfYearisshownbelow.Thepartincolorisnew.Wehaveomittedsomecommentstosavespace,butallthecommentsshowninDisplay8.2shouldbeincludedinthisdefinition. classDayOfYear { public: friendboolequal(DayOfYeardate1,DayOfYeardate2); friendboolafter(DayOfYeardate1,DayOfYeardate2); //Precondition: date1anddate2havevalues. //Returnstrueifdate1followsdate2onthecalendar;otherwise,returnsfalse. DayOfYear(intthe_month,intthe_day); DayOfYear(); voidinput(); voidoutput(); intget_month(); intget_day(); private: voidcheck_date(); intmonth; intday; }; Youalsomustaddthefollowingdefinitionofthefunctionafter: boolafter(DayOfYeardate1,DayOfYeardate2) { return((date1.month>date2.month)|| ((date1.month==date2.month)&&(date1.day>date2.day))); } 4.ThemodifieddefinitionoftheclassMoneyisshownhere.Thepartincolorisnew.Wehaveomittedsomecommentstosavespace,butallthecommentsshowninDisplay8.3shouldbeincludedinthisdefinition. classMoney { public: friendMoneyadd(Moneyamount1,Moneyamount2); friendMoneysubtract(Moneyamount1,Moneyamount2); //Precondition: amount1andamount2havevalues.Returnsamount1minusamount2. friendboolequal(Moneyamount1,Moneyamount2); Money(longdollars,intcents); Money(longdollars); Money(); doubleget_value(); voidinput(istream&ins); voidoutput(ostream&outs); private: longall_cents; }; Youalsomustaddthefollowingdefinitionofthefunctionsubtract: Moneysubtract(Moneyamount1,Moneyamount2) { Moneytemp; temp.all_cents=amount1.all_cents−amount2.all_cents; returntemp; } 5.ThemodifieddefinitionoftheclassMoneyisshownhere.Thepartincolorisnew.Wehaveomittedsomecommentstosavespace,butallthecommentsshowninDisplay8.3shouldbeincludedinthisdefinition. classMoney { public: friendMoneyadd(Moneyamount1,Moneyamount2); friendboolequal(Moneyamount1,Moneyamount2); Money(longdollars,intcents); Money(longdollars); Money(); doubleget_value(); voidinput(istream&ins); voidoutput(ostream&outs); //Precondition: Ifoutsisafileoutputstream,then //outshasalreadybeenconnectedtoafile. //Postcondition: Adollarsignandtheamountofmoney //recordedinthecallingobjecthasbeensenttotheoutputstreamouts. voidoutput(); //Postcondition: Adollarsignandtheamountofmoney //recordedinthecallingobjecthasbeenoutputtothescreen. private: longall_cents; }; Youalsomustaddthefollowingdefinitionofthefunctionnameoutput. (Theolddefinitionofoutputstays,sothattherearetwodefinitionsofoutput.) voidMoney: : output() { output(cout); } Thefollowinglongerversionofthefunctiondefinitionalsoworks: //Usescstdlibandiostream voidMoney: : output() { longpositive_cents,dollars,cents; positive_cents=labs(all_cents); dollars=positive_cents/100; cents=positive_cents%100; if(all_cents<0) cout<<"−$"< else cout<<"$"< if(cents<10) cout<<'0'; cout< } Youcanalsooverloadthememberfunctioninputsothatacalllike purse.input(); meansthesameas purse.input(cin); And,ofcourse,youcancombinethisenhancementwiththeenhancementsfrompreviousSelf-TestExercisestoproduceonehighlyimprovedclassMoney. 6.Iftheuserenters$−9.95(insteadof−$9.95),thefunctioninputwillreadthe‘$’asthevalueofone_char,the−9asthevalueofdollars,the‘.’Asthevalueofdecimal_point,andthe‘9’and‘5’asthevaluesofdigit1anddigit2.Thatmeansitwillsetdollarsequalto−9andcentsequalto95andsosettheamountequaltoavaluethatrepresents−$9.00plus0.95whichis−$8.05.Onewaytocatchthisproblemistotestifthevalueofdollarsisnegative(sincethevalueofdollarsshouldbeanabsolutevalue).Todothis,rewritetheerrormessageportionasfollows: if(one_char! ='$'||decimal_point! ='.'||! isdigit(digit1)||! isdigit(digit2) ||dollars<0)<-------New { cout<<"Errorillegalformformoneyinput\n"; exit (1); } Thiscodestillwillnotgiveanerrormessageforincorrectinputwithzerodollarsasin$−0.95.However,withthematerialwehavelearnedthusfar,atestforthiscase,whilecertainlypossible,wouldsignificantlycomplicatethecodeandmakeithardertoread. 7.#include usingnamespacestd; intmain() { intx; cin>>x; cout< return0; } Ifthecompilerinterpretsinputwithaleading0asabase-eightnumeral,thenwithinputdata077,theoutputshouldbe63.Theoutputshouldbe77ifthecompilerdoesnotinterpretdatawithaleading0asindicatingbaseeight. 8.TheonlychangefromtheversiongiveninDisplay8.3isthatthemodifierconstisaddedtothefunctionheading,sothedefinitionis doubleMoney: : get_value()const { return(all_cents*0.01); } 9.Thememberfunctioninputchangesthevalueofitscallingobject,andsothecompilerwillissueanerrormessageifyouaddtheconstmodifier. 10.Similarities: Eachparametercallmethodprotectsthecaller’sargumentfromchange.Differences: Thecall-by-valuemakesacopyofthecaller’sargument,soitusesmorememorythanacall-by-constant-reference. 11.Intheconstintx=17;declaration,theconstkeywordpromisesthecompilerthatcodewrittenbytheauthorwillnotchangethevalueofx. Intheintf()const;declaration,theconstkeywordisapromisetothecompilerthatcodewrittenbytheauthortoimplementfunctionfwillnotchangeanythinginthecallingobject. Intheintg(constA&x);declaration,theconstkeywordisapromisetothecompilerthatcodewrittenbytheclassauthorwillnotchangetheargumentpluggedinforx. 12.Thedifferencebetweena(binary)operator(suchas+,*,/,andsoforth)andafunctioninvolvesthesyntaxofhowtheyarecalled.Inafunctioncall,theargumentsaregiveninparenthesesafterthefunctionname.Withanoperator,theargumentsaregivenbeforeandaftertheoperator.Also,youmustusethereservedwordoperatorinthedeclarationandinthedefinitionofanoverloadedoperator. 13.ThemodifieddefinitionoftheclassMoneyisshownhere.Thepartincolor isnew.Wehaveomittedsomecommentstosavespace,butallthecomments showninDisplay8.5shouldbeincludedinthisdefinition. classMoney { public: friendMoneyoperator+(constMoney&amount1,constMoney&amount2); friendbooloperator==(constMoney&amount1,constMoney&amount2); friendbooloperator<(constMoney&amount1,constMoney&amount2); //Precondition: amount1andamount2havebeengivenvalues. //Returnstrueifamount1islessthanamount2;otherwise,returnsfalse. Money(longdollars,intcents); Money(longdollars); Money(); doubleget_value()const; voidinput(istream&ins); voidoutput(ostream&outs)const; private: longall_cents; }; Youalsomustaddthefollowingdefinitionoftheoverloadedoperator<: booloperator<(constMoney&amount1,constMoney&amount2) { return(amount1.all_cents } 14.ThemodifieddefinitionoftheclassMoneyisshownhere.Thepartincolorisnew.Wehaveomittedsomecommentstosavespace,butallthecommentsshowninDisplay8.5shouldbeincludedinthisdefinition.Wehaveincludedthechangesfromthepreviousexercisesinthisanswer,sinceitisnaturaltousetheoverloaded classMoney { public: friendMoneyoperator+(constMoney&amount1,constMoney&amount2); friendbooloperator==(constMoney&amount1,constMoney&amount2); friendbooloperator<(constMoney&amount1,constMoney&amount2); //Precondition: amount1andamount2havebeengiven //values. //Returnstrueifamount1islessthanamount2; //otherwise,returnsfalse. friendbooloperator<=(constMoney&amount1,constMoney&amount2); //Precondition: amount1andamount2havebeengiven //values. //Returnstrueifamount1islessthanorequalto //amount2;otherwise,returnsfalse. Money(longdollars,intcents); Money(longdollars); Money(); doubleget_value()const; voidinput(istream&ins); voidoutput(ostream&outs)const; private: longall_cents; }; Youalsomustaddthefollowingdefinitionoftheoverloadedoperator<=(aswellasthedefinitionoftheoverloadedoperator booloperator<=(constMoney&amount1,constMoney&amount2) { return((amount1.all_cents } 15.Whenoverloadinganoperator,atleastoneoftheargumentstotheoperatormustbeofaclasstype.Thi
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- ch08