ch08.docx

上传人:b****4 文档编号:27535971 上传时间:2023-07-02 格式:DOCX 页数:15 大小:18.65KB
下载 相关 举报
ch08.docx_第1页
第1页 / 共15页
ch08.docx_第2页
第2页 / 共15页
ch08.docx_第3页
第3页 / 共15页
ch08.docx_第4页
第4页 / 共15页
ch08.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

ch08.docx

《ch08.docx》由会员分享,可在线阅读,更多相关《ch08.docx(15页珍藏版)》请在冰豆网上搜索。

ch08.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1