Tải bản đầy đủ - 0 (trang)
Chapter 10. Classes: A Deeper Look, Part 2

Chapter 10. Classes: A Deeper Look, Part 2

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

Chapter10.Classes:ADeeperLook,Part

2

Butwhat,toserveourprivateends,Forbidsthe

cheatingofourfriends?

CharlesChurchill

Insteadofthisabsurddivisionintosexestheyought

toclasspeopleasstaticanddynamic.

EvelynWaugh

Havenofriendsnotequaltoyourself.

Confucius

OBJECTIVES

Inthischapteryouwilllearn:

Tospecifyconst(constant)objectsandconstmember

functions.

Tocreateobjectscomposedofotherobjects.

Tousefriendfunctionsandfriendclasses.

Tousethethispointer.

Tocreateanddestroyobjectsdynamicallywithoperatorsnew

anddelete,respectively.



Tousestaticdatamembersandmemberfunctions.

Theconceptofacontainerclass.

Thenotionofiteratorclassesthatwalkthroughthe

elementsofcontainerclasses.

Touseproxyclassestohideimplementationdetailsfroma

class'sclients.



[Page524]

Outline

10.1Introduction

10.2const(Constant)ObjectsandconstMemberFunctions

10.3Composition:ObjectsasMembersofClasses

10.4friendFunctionsandfriendClasses

10.5UsingthethisPointer

10.6DynamicMemoryManagementwithOperatorsnewand

delete



10.7staticClassMembers

10.8DataAbstractionandInformationHiding

10.8.1Example:ArrayAbstractDataType

10.8.2Example:StringAbstractDataType

10.8.3Example:QueueAbstractDataType



10.9ContainerClassesandIterators

10.10ProxyClasses

10.11Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page524(continued)]



10.1.Introduction

Inthischapter,wecontinueourstudyofclassesanddata

abstractionwithseveralmoreadvancedtopics.Weuseconst

objectsandconstmemberfunctionstopreventmodificationsof

objectsandenforcetheprincipleofleastprivilege.Wediscuss

compositionaformofreuseinwhichaclasscanhaveobjectsof

otherclassesasmembers.Next,weintroducefriendship,which

enablesaclassdesignertospecifynon-memberfunctionsthat

canaccessclass'snon-publicmembersatechniquethatisoften

usedinoperatoroverloading(Chapter11)forperformance

reasons.Wediscussaspecialpointer(calledthis),whichisan

implicitargumenttoeachofaclass'snon-staticmember

functionsthatallowsthosememberfunctionstoaccessthe

correctobject'sdatamembersandothernon-staticmember

functions.Wethendiscussdynamicmemorymanagementand

showhowtocreateanddestroyobjectsdynamicallywiththe

newanddeleteoperators.Next,wemotivatetheneedforstatic

classmembersandshowhowtousestaticdatamembersand

memberfunctionsinyourownclasses.Finally,weshowhowto

createaproxyclasstohidetheimplementationdetailsofa

class(includingitsprivatedatamembers)fromclientsofthe

class.

RecallthatChapter3introducedC++StandardLibraryclass

stringtorepresentstringsasfull-fledgedclassobjects.Inthis

chapter,however,weusethepointer-basedstringswe

introducedinChapter8tohelpthereadermasterpointersand

preparefortheprofessionalworldinwhichthereaderwillseea

greatdealofClegacycodeimplementedoverthelasttwo

decades.Thus,thereaderwillbecomefamiliarwiththetwo

mostprevalentmethodsofcreatingandmanipulatingstringsin

C++.



[Page524(continued)]



10.2.const(Constant)Objectsandconst

MemberFunctions

Wehaveemphasizedtheprincipleofleastprivilegeasoneof

themostfundamentalprinciplesofgoodsoftwareengineering.

Letusseehowthisprincipleappliestoobjects.



[Page525]

Someobjectsneedtobemodifiableandsomedonot.The

programmermayusekeywordconsttospecifythatanobjectis

notmodifiableandthatanyattempttomodifytheobjectshould

resultinacompilationerror.Thestatement

constTimenoon(12,0,0);



declaresaconstobjectnoonofclassTimeandinitializesitto12

noon.



SoftwareEngineeringObservation10.1

Declaringanobjectasconsthelpsenforcetheprincipleof

leastprivilege.Attemptstomodifytheobjectarecaught

atcompiletimeratherthancausingexecution-time

errors.Usingconstproperlyiscrucialtoproperclass

design,programdesignandcoding.



PerformanceTip10.1

Declaringvariablesandobjectsconstcanimprove

performancetoday'ssophisticatedoptimizingcompilers

canperformcertainoptimizationsonconstantsthat

cannotbeperformedonvariables.



C++compilersdisallowmemberfunctioncallsforconstobjects

unlessthememberfunctionsthemselvesarealsodeclared

const.Thisistrueevenforgetmemberfunctionsthatdonot

modifytheobject.Inaddition,thecompilerdoesnotallow

memberfunctionsdeclaredconsttomodifytheobject.

Afunctionisspecifiedasconstbothinitsprototype(Fig.10.1;

lines1924)andinitsdefinition(Fig.10.2;lines47,53,59and

65)byinsertingthekeywordconstafterthefunction's

parameterlistand,inthecaseofthefunctiondefinition,before

theleftbracethatbeginsthefunctionbody.



Figure10.1.Timeclassdefinitionwithconst

memberfunctions.

(Thisitemisdisplayedonpage526intheprintversion)



1//Fig.10.1:Time.h

2//DefinitionofclassTime.

3//MemberfunctionsdefinedinTime.cpp.

4#ifndefTIME_H

5#defineTIME_H

6

7classTime

8{

9public:

10Time(int=0,int=0,int=0);//defaultconstructor

11

12//setfunctions



13voidsetTime(int,int,int);//settime

14voidsetHour(int);//sethour

15voidsetMinute(int);//setminute

16voidsetSecond(int);//setsecond

17

18//getfunctions(normallydeclaredconst)

19intgetHour()const;//returnhour

20intgetMinute()const;//returnminute

21intgetSecond()const;//returnsecond

22

23//printfunctions(normallydeclaredconst)

24voidprintUniversal()const;//printuniversaltime

25voidprintStandard();//printstandardtime(shouldbeconst)

26private:

27inthour;//0-23(24-hourclockformat)

28intminute;//0-59

29intsecond;//0-59

30};//endclassTime

31

32#endif



Figure10.2.Timeclassmember-function

definitions,includingconstmemberfunctions.

(Thisitemisdisplayedonpages527-528intheprint

version)



1//Fig.10.2:Time.cpp

2//Member-functiondefinitionsforclassTime.

3#include

4usingstd::cout;

5

6#include

7usingstd::setfill;

8usingstd::setw;

9

10#include"Time.h"//includedefinitionofclassTime

11

12//constructorfunctiontoinitializeprivatedata;

13//callsmemberfunctionsetTimetosetvariables;

14//defaultvaluesare0(seeclassdefinition)

15Time::Time(inthour,intminute,intsecond)

16{

17setTime(hour,minute,second);

18}//endTimeconstructor

19

20//sethour,minuteandsecondvalues



21voidTime::setTime(inthour,intminute,intsecond)

22{

23setHour(hour);

24setMinute(minute);

25setSecond(second);

26}//endfunctionsetTime

27

28//sethourvalue

29voidTime::setHour(inth)

30{

31hour=(h>=0&&h<24)?h:0;//validatehour

32}//endfunctionsetHour

33

34//setminutevalue

35voidTime::setMinute(intm)

36{

37minute=(m>=0&&m<60)?m:0;//validateminute

38}//endfunctionsetMinute

39

40//setsecondvalue

41voidTime::setSecond(ints)

42{

43second=(s>=0&&s<60)?s:0;//validatesecond

44}//endfunctionsetSecond

45

46//returnhourvalue

47intTime::getHour()const//getfunctionsshouldbeconst

48{

49returnhour;

50}//endfunctiongetHour

51

52//returnminutevalue

53intTime::getMinute()const

54{

55returnminute;

56}//endfunctiongetMinute

57

58//returnsecondvalue

59intTime::getSecond()const

60{

61returnsecond;

62}//endfunctiongetSecond

63

64//printTimeinuniversal-timeformat(HH:MM:SS)

65voidTime::printUniversal()const

66{

67cout<
68<
69}//endfunctionprintUniversal

70

71//printTimeinstandard-timeformat(HH:MM:SSAMorPM)

72voidTime::printStandard()//notelackofconstdeclaration

73{

74cout<<((hour==0||hour==12)?12:hour%12)

75<<":"<
76<<":"<


77}//endfunctionprintStandard



CommonProgrammingError10.1

Definingasconstamemberfunctionthatmodifiesadata

memberofanobjectisacompilationerror.



CommonProgrammingError10.2

Definingasconstamemberfunctionthatcallsanon-const

memberfunctionoftheclassonthesameinstanceofthe

classisacompilationerror.



CommonProgrammingError10.3

Invokinganon-constmemberfunctiononaconstobjectis

acompilationerror.



SoftwareEngineeringObservation10.2

Aconstmemberfunctioncanbeoverloadedwithanon-



constversion.Thecompilerchooseswhichoverloaded



memberfunctiontousebasedontheobjectonwhichthe

functionisinvoked.Iftheobjectisconst,thecompiler

usestheconstversion.Iftheobjectisnotconst,the

compilerusesthenon-constversion.



Aninterestingproblemarisesforconstructorsanddestructors,

eachofwhichtypicallymodifiesobjects.Theconstdeclarationis

notallowedforconstructorsanddestructors.Aconstructor

mustbeallowedtomodifyanobjectsothattheobjectcanbe

initializedproperly.Adestructormustbeabletoperformits

terminationhousekeepingchoresbeforeanobject'smemoryis

reclaimedbythesystem.



[Page526]

CommonProgrammingError10.4

Attemptingtodeclareaconstructorordestructorconstis

acompilationerror.



DefiningandUsingconstMemberFunctions

TheprogramofFigs.10.110.3modifiesclassTimeofFigs.

9.99.10bymakingitsgetfunctionsandprintUniversalfunction

const.IntheheaderfileTime.h(Fig.10.1),lines1921and24

nowincludekeywordconstaftereachfunction'sparameterlist.



ThecorrespondingdefinitionofeachfunctioninFig.10.2(lines

47,53,59and65,respectively)alsospecifieskeywordconst

aftereachfunction'sparameterlist.

Figure10.3instantiatestwoTimeobjectsnon-constobjectwakeUp

(line7)andconstobjectnoon(line8).Theprogramattemptsto

invokenon-constmemberfunctionssetHour(line13)and

printStandard(line20)ontheconstobjectnoon.Ineachcase,the

compilergeneratesanerrormessage.Theprogramalso

illustratesthethreeothermember-function-callcombinations

onobjectsanon-constmemberfunctiononanon-constobject

(line11),aconstmemberfunctiononanon-constobject(line

15)andaconstmemberfunctiononaconstobject(lines1718).

Theerrormessagesgeneratedfornon-constmemberfunctions

calledonaconstobjectareshownintheoutputwindow.Notice

that,althoughsomecurrentcompilersissueonlywarning

messagesforlines13and20(thusallowingthisprogramtobe

executed),weconsiderthesewarningstobeerrorsthe

ANSI/ISOC++standarddisallowstheinvocationofanon-const

memberfunctiononaconstobject.



[Page527]

Figure10.3.constobjectsandconstmember

functions.

(Thisitemisdisplayedonpages528-529intheprint

version)



1//Fig.10.3:fig10_03.cpp

2//Attemptingtoaccessaconstobjectwithnon-constmemberfunctions.

3#include"Time.h"//includeTimeclassdefinition

4

5intmain()

6{

7TimewakeUp(6,45,0);//non-constantobject

8constTimenoon(12,0,0);//constantobject

9



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

Chapter 10. Classes: A Deeper Look, Part 2

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

×