Tải bản đầy đủ - 0 (trang)
Chapter 15. Special Topics: Friends, Operator Overloading, Macros, and Inline Functions

Chapter 15. Special Topics: Friends, Operator Overloading, Macros, and Inline Functions

Tải bản đầy đủ - 0trang

Chapter15.SpecialTopics:Friends,

OperatorOverloading,Macros,andInline

Functions

OBJECTIVES

Todeclareandcodeafriendfunctionforaclass

Todecidewhenanoverloadedoperatorshouldbeaclass

memberfunctionorafriend

Toknowwhichoperatorscannotbeoverloaded

Toknowwhichoverloadedoperatorsmustbeclass

members

Tooverloadthebasicarithmeticoperators

Toknowthemeaningofthethispointer

Tooverloadtheassignmentoperator

Tooverloadtheinsertionandextractionoperators

Tooverloadthecompoundassignmentoperators

Tooverloadtherelationaloperators

Tooverloadtheunaryoperators++and-Thischaptercoversseveraltopicsthatsupplementmaterialin



earlierchapters.Sections15.1through15.8extendthe

materialofChapter12.Theyshowhowtousefriendfunctions

andhowtoexpandtheuseofmanyoperatorsthrough

overloading.Section15.8extendsthematerialofChapter5by

discussinginlinefunctionsandtheuseofmacros.



[Page731]



15.1.friendFunctions

Sofar,wehavelearnedthattheclassmethodsaretheonly

functionsthathaveaccesstotheprivateinstancevariablesof

thatclass.However,therearetimeswhenitisdesirablefora

functionthatisnotaclassmethodtohaveaccesstotheprivate

instancevariablesofaclass.



15.1.1.DefiningafriendFunction

SupposethatinasystemthatusestheSavings_Accountclass,we

wanttoimplementafunctionthattransfersmoneyfromone

accountintoanother.Apossiblesolutionwouldbetowritea

Savings_Accountmethod,TRansfer_Method.Themethodwouldhave

twoarguments:thefirstistheaccountwearetransferring

fundsfrom,andthesecondargumentwouldbetheamountof

moneytotransfer.Theaccounttowhichweapplythemethod

wouldbetheaccounttowhichwearetransferringfunds.For

example,ifacc1andacc2areaccounts,thefollowingstatement

wouldtransfer$100.00fromacc2toacc1.

acc1.Transfer_Method(acc2,100.00);



Althoughthisapproachworks,thewayinwhichweusethe

methodmightseemabitawkward.Anotherapproachwouldbe

todefineanonmemberfunctionTRansfer1()thattakesthree

arguments:thefirstistheaccountreceivingthefunds,the

secondistheaccountgivingthefunds,andthethirdisthe

amountofthetransfer.Thus,totransfer$100.00fromacc2to

acc1,wewouldcodethefollowingstatement.



Transfer1(acc1,acc2,100);



WecanusethemethodsofSavings_Accounttocodesucha

function.ThefunctionreturnsTRueifthetransferissuccessfully

madeandfalseotherwise.



boolTransfer1(Savings_Accountacc1,Savings_Accountacc2,doub

{

if(!acc2.Withdraw(amount))

returnfalse;

acc1.Deposit(amount);

returntrue;

}



RecallthatWithdraw()returnsTRueifthewithdrawalismadeand

falseotherwise.Theifstatementintransfer1()returnsfalseif

thewithdrawalisnotmade.Anobjectiontothisimplementation

ofatransferfunctionisthatthefunctionrequiresexecutingtwo

otherfunctions,namely,Withdraw()andDeposit().Thefunction

wouldbemoreefficientifitcoulddirectlyaccesstheinstance

variablesoftheparametersacc1andacc2.

Thesolutionistocreateafriendfunction.Afriendfunctionofa

classhasthesameaccessprivilegesastheclassmethods,but

isnotitselfamethod.Therefore,afriendfunctionofaclasshas

accesstoalltheprivatemembersoftheclassjustasthoughit

wereaclassmethod.Itisimportanttonotethataclassmust

declareafunctiontobeafriend,nottheotherwayaround.It

wouldviolatetheprincipleofdatahidingifanyfunctioncould

declareitselfafriendofaclass!Tocreateafriendfunction,

followtheprocedureofNote15.1.



[Page732]

Note15.1HowtoWriteafriend

Function

Todeclareafunctiontobeafriendfunctionofa

class:

Declarethefunctioninsidetheclassdeclaration

andprecedethereturntypeofthefunctionwith

thekeywordfriend.Itdoesnotmatterinwhich

accesscategoryyoudefinethefunction(public

orprivate).

Whenyoudefinethefunctionoutsidetheclass,

donotrepeatthekeywordfriend.Thekeyword

friendcanappearonlyinaclassdeclaration.



Thus,inthedeclarationofSavings_Account,wewouldcodethe

following.



classSavings_Account

{

friendboolTransfer(Savings_Account&,Savings_Account&,doub

private:

.

.

.

public:

.

.



.

};



Notethatweplacethedeclarationofthefriendfunctionbefore

eitheraccessspecifier.Wepassthetwoaccountstothefunction

byreferencebecausethefunctionmustchangebothAccount

objectsthatarepassedasarguments.Ifwepassthe

Savings_Accountobjectsbyvalue,thechangesmadebythe

functionwouldbemadetothefunction'sparameters(whichare

copiesofthearguments)andnottotheargumentsthemselves.

SeeExperiment1.Thecodeforthefunctionfollows.



boolTransfer(Savings_Account&acc_r1,Savings_Account&acc_r2,

{

//Ifamountexceedsacc_r2'sbalance,donothingandreturnf

if(amount>acc_r2.balance)

returnfalse;

//Otherwise,makethetransferandreturntrue



acc_r2.balance=amount;//decreaseacc_r2'sbalancebyamou

acc_r1.balance+=amount;//increaseacc_r1'sbalancebyamo

returntrue;

}



[Page733]

Thisfunctionissomewhatlongerthantransfer1(),butitismore

efficientbecauseitdoesnothavetoexecutefunctionsto

performitstask.Notethatwecandirectlyaccesstheprivate

datamembersofbothaccountsbecausetransfer()isafriendof



Savings_Account.Wemustusethedotoperatortoaccessthe



datamembersofbothparametersbecauseTRansfer()isnota

classmethod.

Followingisacompleteprogramthatusesthetransfer()

function.Itisbasedonprogramdem12-13.cpp.Tosimplifythe

program,wehaveremovedtheCalc_Interest(),Deposit(),and

Withdraw()methods.

//dem15-1.cpp

//Thisprogramillustratesafriendfunction.

//Itisbasedondem12-13.cpp.

//TosimplifytheprogramtheCalc_Interest(),Deposit()

//andWithdraw()methodshavebeenremoved.

#include

#include

#include

usingnamespacestd;



classSavings_Account

{

friendboolTransfer(Savings_Account&,Savings_Account&,doub

private:

charid_no[5];

char*name;

doublebalance;

doublerate;



public:

Savings_Account(charid[],char*n_p,doublebal=0.00,do

~Savings_Account();

constchar*Get_Id()const;



constchar*Get_Name()const;

doubleGet_Balance();

};



Savings_Account::Savings_Account(charid[],char*n_p,doubleb

{

strcpy(id_no,id);//copyfirstargumentintoid_no[]



name=newchar[strlen(n_p)+1];//createspaceforthename

strcpy(name,n_p);//copysecondargumentintonewspace

balance=bal;

rate=rt;

}



[Page734]



Savings_Account::~Savings_Account()

{

cout<
cout<<"Account"<
delete[]name;

}

constchar*Savings_Account::Get_Id()const

{

returnid_no;

}

constchar*Savings_Account::Get_Name()const

{

returnname;

}

doubleSavings_Account::Get_Balance()

{

returnbalance;

}

boolTransfer(Savings_Account&acc_r1,Savings_Account&acc_r2,

{



//Ifamountexceedsacc_r2'sbalance,donothingandreturn0

if(amount>acc_r2.balance)

returnfalse;

//Otherwise,makethetransferandreturn1



acc_r2.balance=amount;//decreaseacc_r2'sbalancebyamou

acc_r1.balance+=amount;//increaseacc_r1'sbalancebyamo

returntrue;

}



voidDisplay_Account(Savings_Account&);//Functionprototype

intmain()

{

cout<
<
<
doubleamount;

Savings_Accountacc1("1111","AdamZapple",100.00,0.08);

Savings_Accountacc2("2222","PolyEster",200.00,0.06);

Display_Account(acc1);

Display_Account(acc2);



cout<
cout<<"Enteranamounttotransferfromthesecondaccount

<<"tothefirst:";



[Page735]

cin>>amount;

if(Transfer(acc1,acc2,amount))

{



cout<
cout<<"Transfermade.UpdatedAccountInformation:"<
Display_Account(acc1);

Display_Account(acc2);

}

else

{

cout<
cout<<"Transfercouldnotbemade."<
}

return0;

}



voidDisplay_Account(Savings_Account&acc)

{

cout<
cout<<"DataforAccount#"<
cout<<"Owner'sName:"<


cout<<"AccountBalance:"<
}



[Page736]

ProgramOutputRun1



[Viewfullwidth]

DataforAccount#1111

Owner'sName:AdamZapple

AccountBalance:100.00



DataforAccount#2222

Owner'sName:PolyEster

AccountBalance:200.00

Enteranamounttotransferfromthesecond

accounttothefirst:40.50

Transfermade.UpdatedAccountInformation:

DataforAccount#1111

Owner'sName:AdamZapple

AccountBalance:140.50

DataforAccount#2222



[Page736]

Owner'sName:PolyEster

AccountBalance:159.50

Account2222terminated.

Account1111terminated.



Notehowmain()usesthefunctionTRansfer().Theifstatement

teststoseeifthetransferwassuccessful.Ifso,theprogram

displaysamessageandthenewaccountinformation.Ifthe

transferwasnotsuccessful,theprogramdisplaysan

appropriatemessage.Followingisaprogramruninwhichwe

trytotransfermoremoneyfromthefirstaccountthanisinthe

account.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 15. Special Topics: Friends, Operator Overloading, Macros, and Inline Functions

Tải bản đầy đủ ngay(0 tr)

×