Tải bản đầy đủ - 0 (trang)
Chapter 15. FRIENDS, EXCEPTIONS, AND MORE

Chapter 15. FRIENDS, EXCEPTIONS, AND MORE

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

donotsupportthem.



Friends

Severalexamplesinthisbookhaveusedfriendfunctionsas

partoftheextendedinterfaceforaclass.Suchfunctionsare

nottheonlykindsoffriendsaclasscanhave.Aclassalsocan

beafriend.Inthatcase,anymethodofthefriendclasscan

accessprivateandprotectedmembersoftheoriginalclass.

Also,youcanbemorerestrictiveanddesignatejustparticular

memberfunctionsofaclasstobefriendstoanotherclass.A

classdefineswhichfunctions,memberfunctions,orclassesare

friends;friendshipcannotbeimposedfromtheoutside.Thus,

althoughfriendsdograntoutsideaccesstoaclass'sprivate

portion,theydon'treallyviolatethespiritofobject-oriented

programming.Instead,theyprovidemoreflexibilitytothe

publicinterface.



FriendClasses

Whenmightyouwanttomakeoneclassafriendtoanother?

Let'slookatanexample.Supposeyoumustprogramasimple

simulationofatelevisionandaremotecontrol.Youdecideto

defineaTvclassrepresentingatelevisionandaRemoteclass

representingaremotecontrol.Clearly,thereshouldbesome

sortofrelationshipbetweentheseclasses,butwhatkind?A

remotecontrolisnotatelevisionandviceversa,sotheis-a

relationshipofpublicinheritancedoesn'tapply.Noriseithera

componentoftheother,sothehas-arelationshipof

containmentorofprivateorprotectedinheritancedoesn't

apply.Whatistrueisthataremotecontrolcanmodifythestate

ofatelevision,andthissuggestsmakingtheRemoteclassa

friendtotheTvclass.

First,let'sdefinetheTvclass.Youcanrepresentatelevision

withasetofstatemembers,thatis,variablesthatdescribe



variousaspectsofthetelevision.Herearesomeofthepossible

states:

On-off

Channelsetting

Volumesetting

Cableorantennatuningmode

TVtunerorVCRinput

Thetuningmodereflectsthefactthat,intheU.S.,thespacing

betweenchannelsforchannels14andupisdifferentforcable

receptionthanitisforUHFbroadcastreception.Theinput

selectionchoosesbetweenTV,whichcouldbeeithercableor

broadcastTV,andaVCR.Somesetsmayoffermorechoices,

butthislistisenoughforourpurposes.

Also,atelevisionhassomeparametersthataren'tstate

variables.Forexample,televisionsvaryinthenumberof

channelstheycanreceive,andyoucanincludeamemberto

trackthatvalue.

Next,youmustprovidetheclasswithmethodsforaltering

thesesettings.Manytelevisionsetsthesedayshidetheir

controlsbehindpanels,butit'sstillpossiblewithmost

televisionstochangechannels,andsoon,withoutaremote

control.However,oftenyoucangoupordownonechannelata

timebutcan'tselectachannelatrandom.Similarly,there's

usuallyabuttonforincreasingthevolumeandonefor

decreasingthevolume.

Aremotecontrolshouldduplicatethecontrolsbuiltintothe

television.ManyofitsmethodscanbeimplementedbyusingTv



methods.Inaddition,aremotecontroltypicallyprovides

randomaccesschannelselection.Thatis,youcangodirectly

fromchannel2tochannel20withoutgoingthroughallthe

interveningchannels.Also,manyremotescanworkintwo

modesasatelevisioncontrollerandasaVCRcontroller.

Theseconsiderationssuggestadefinitionlikethatshownin

Listing15.1.Thedefinitionincludesseveralconstantsdefined

asenumerations.ThestatementmakingRemoteafriendclassis

this:

friendclassRemote;

Afrienddeclarationcanappearinapublic,private,orprotected

section;thelocationmakesnodifference.BecausetheRemote

classmentionstheTvclass,thecompilerhastoknowaboutthe

TvclassbeforeitcanhandletheRemoteclass.Thesimplest

waytoaccomplishthisistodefinetheTvclassfirst.

Alternatively,youcanuseaforwarddeclaration;we'lldiscuss

thatoptionsoon.



CompatibilityNote

Ifyourcompilerdoesn'tsupportthebooltype,useint,0,and1

insteadofbool,false,andtrue.



Listing15.1tv.h



//tv.h--TvandRemoteclasses

#ifndefTV_H_

#defineTV_H_



classTv

{

public:



friendclassRemote;//RemotecanaccessTvprivatepart

enum{Off,On};

enum{MinVal,MaxVal=20};

enum{Antenna,Cable};

enum{TV,VCR};



Tv(ints=Off,intmc=100):state(s),volume(5),

maxchannel(mc),channel(2),mode(Cable),input(TV){}

voidonoff(){state=(state==On)?Off:On;}

boolison()const{returnstate==On;}

boolvolup();

boolvoldown();



voidchanup();

voidchandown();



voidset_mode(){mode=(mode==Antenna)?Cable:Antenna;

voidset_input(){input=(input==TV)?VCR:TV;}

voidsettings()const;//displayallsettings

private:

intstate;//onoroff

intvolume;//assumedtobedigitized

intmaxchannel;//maximumnumberofchannels

intchannel;//currentchannelsetting

intmode;//broadcastorcable

intinput;//TVorVCR

};



classRemote

{

private:

intmode;//controlsTVorVCR



public:

Remote(intm=Tv::TV):mode(m){}

boolvolup(Tv&t){returnt.volup();}

boolvoldown(Tv&t){returnt.voldown();}

voidonoff(Tv&t){t.onoff();}

voidchanup(Tv&t){t.chanup();}

voidchandown(Tv&t){t.chandown();}

voidset_chan(Tv&t,intc){t.channel=c;}

voidset_mode(Tv&t){t.set_mode();}

voidset_input(Tv&t){t.set_input();}

};

#endif

Mostoftheclassmethodsaredefinedinline.Notethateach

Remotemethodotherthantheconstructortakesareferenceto

aTvobjectasanargument.Thatreflectsthataremotehasto

beaimedataparticularTV.Listing15.2showstheremaining

definitions.Thevolume-settingfunctionschangethevolume

memberbyoneunitunlessthesoundhasreacheditsminimum

ormaximumsetting.Thechannelselectionfunctionsuse

wraparound,withthelowestchannelsetting,takentobe1,

immediatelyfollowingthehighestchannelsetting,maxchannel.

Manyofthemethodsusetheconditionaloperatortotogglea

statebetweentwosettings:



voidonoff(){state=(state==On)?Off:On;}

Providedthatthetwostatevaluesare0and1,thiscanbedone

morecompactlyusingthecombinedbitwiseexclusiveORand

assignmentoperator(^=)discussedinAppendixE,"Other

Operators:"

voidonoff(){state^=1;}

Infact,youcouldstoreuptoeightbivalentstatesettingsina

singleunsignedcharvariableandtogglethemindividually,but

that'sanotherstory,onemadepossiblebythebitwiseoperators

discussedinAppendixE.



Listing15.2tv.cpp



//tv.cpp--methodsfortheTvclass(Remotemethodsareinlin

#include

usingnamespacestd;

#include"tv.h"



boolTv::volup()

{

if(volume


{

volume++;

returntrue;

}

else

returnfalse;

}

boolTv::voldown()

{

if(volume>MinVal)

{

volume--;

returntrue;

}

else

returnfalse;

}



voidTv::chanup()

{

if(channel
channel++;

else

channel=1;

}



voidTv::chandown()

{

if(channel>1)

channel--;

else

channel=maxchannel;

}



voidTv::settings()const

{

cout<<"TVis"<<(state==Off?"Off":"On")<<'\n';



if(state==On)

{

cout<<"Volumesetting="<
cout<<"Channelsetting="<
cout<<"Mode="

<<(mode==Antenna?"antenna":"cable")<<'\n';

cout<<"Input="

<<(input==TV?"TV":"VCR")<<'\n';

}

}

Next,Listing15.3isashortprogramthattestssomeofthe

features.Thesamecontrollerisusedtocontroltwoseparate

televisions.



Listing15.3use_tv.cpp



//use_tv.cpp

#include

usingnamespacestd;

#include"tv.h"



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

Chapter 15. FRIENDS, EXCEPTIONS, AND MORE

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

×