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

Chapter 9. Classes: A Deeper Look, Part 1

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

Chapter9.Classes:ADeeperLook,Part

1

MyobjectallsublimeIshallachieveintime.

W.S.Gilbert

Isitaworldtohidevirtuesin?

WilliamShakespeare

Don'tbe"consistent,"butbesimplytrue.

OliverWendellHolmes,Jr.

Thisaboveall:tothineownselfbetrue.

WilliamShakespeare

OBJECTIVES

Inthischapteryouwilllearn:

Howtouseapreprocessorwrappertopreventmultiple

definitionerrorscausedbyincludingmorethanonecopyof

aheaderfileinasource-codefile.

Tounderstandclassscopeandaccessingclassmembersvia

thenameofanobject,areferencetoanobjectorapointer

toanobject.

Todefineconstructorswithdefaultarguments.



Howdestructorsareusedtoperform"termination

housekeeping"onanobjectbeforeitisdestroyed.

Whenconstructorsanddestructorsarecalledandtheorder

inwhichtheyarecalled.

Thelogicerrorsthatmayoccurwhenapublicmember

functionofaclassreturnsareferencetoprivatedata.

Toassignthedatamembersofoneobjecttothoseof

anotherobjectbydefaultmemberwiseassignment.



[Page481]

Outline

9.1Introduction

9.2TimeClassCaseStudy

9.3ClassScopeandAccessingClassMembers

9.4SeparatingInterfacefromImplementation

9.5AccessFunctionsandUtilityFunctions

9.6TimeClassCaseStudy:ConstructorswithDefaultArguments

9.7Destructors

9.8WhenConstructorsandDestructorsAreCalled

9.9TimeClassCaseStudy:ASubtleTrapReturningaReference

toaprivateDataMember

9.10DefaultMemberwiseAssignment



9.11SoftwareReusability

9.12(Optional)SoftwareEngineeringCaseStudy:Startingto

ProgramtheClassesoftheATMSystem

9.13Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page481(continued)]



9.1.Introduction

Intheprecedingchapters,weintroducedmanybasictermsand

conceptsofC++objectorientedprogramming.Wealso

discussedourprogramdevelopmentmethodology:Weselected

appropriateattributesandbehaviorsforeachclassand

specifiedthemannerinwhichobjectsofourclasses

collaboratedwithobjectsofC++StandardLibraryclassesto

accomplisheachprogram'soverallgoals.

Inthischapter,wetakeadeeperlookatclasses.Weusean

integratedTimeclasscasestudyinthischapter(threeexamples)

andChapter10(twoexamples)todemonstrateseveralclass

constructionfeatures.WebeginwithaTimeclassthatreviews

severalofthefeaturespresentedintheprecedingchapters.The

examplealsodemonstratesanimportantC++software

engineeringconceptusinga"preprocessorwrapper"inheader

filestopreventthecodeintheheaderfrombeingincludedinto

thesamesourcecodefilemorethanonce.Sinceaclasscanbe

definedonlyonce,usingsuchpreprocessordirectivesprevents

multipledefinitionerrors.

Next,wediscussclassscopeandtherelationshipsamong

membersofaclass.Wealsodemonstratehowclientcodecan

accessaclass'spublicmembersviathreetypesof"handles"the

nameofanobject,areferencetoanobjectorapointertoan

object.Asyouwillsee,objectnamesandreferencescanbe

usedwiththedot(.)memberselectionoperatortoaccessa

publicmember,andpointerscanbeusedwiththearrow(->)

memberselectionoperator.

Wediscussaccessfunctionsthatcanreadordisplaydatainan

object.Acommonuseofaccessfunctionsistotestthetruthor

falsityofconditionssuchfunctionsareknownaspredicate

functions.Wealsodemonstratethenotionofautilityfunction



(alsocalledahelperfunction)aprivatememberfunctionthat

supportstheoperationoftheclass'spublicmemberfunctions,

butisnotintendedforusebyclientsoftheclass.



[Page482]

InthesecondexampleoftheTimeclasscasestudy,we

demonstratehowtopassargumentstoconstructorsandshow

howdefaultargumentscanbeusedinaconstructortoenable

clientcodetoinitializeobjectsofaclassusingavarietyof

arguments.Next,wediscussaspecialmemberfunctioncalleda

destructorthatispartofeveryclassandisusedtoperform

"terminationhousekeeping"onanobjectbeforetheobjectis

destroyed.Wethendemonstratetheorderinwhich

constructorsanddestructorsarecalled,becauseyourprograms'

correctnessdependsonusingproperlyinitializedobjectsthat

havenotyetbeendestroyed.

OurlastexampleoftheTimeclasscasestudyinthischapter

showsadangerousprogrammingpracticeinwhichamember

functionreturnsareferencetoprivatedata.Wediscusshowthis

breakstheencapsulationofaclassandallowsclientcodeto

directlyaccessanobject'sdata.Thislastexampleshowsthat

objectsofthesameclasscanbeassignedtooneanotherusing

defaultmemberwiseassignment,whichcopiesthedata

membersintheobjectontherightsideoftheassignmentinto

thecorrespondingdatamembersoftheobjectontheleftside

oftheassignment.Thechapterconcludeswithadiscussionof

softwarereusability.



[Page482(continued)]



9.2.TimeClassCaseStudy

Ourfirstexample(Figs.9.19.3)createsclassTimeandadriver

programthatteststheclass.Youhavealreadycreatedseveral

classesinthisbook.Inthissection,wereviewmanyofthe

conceptscoveredinChapter3anddemonstrateanimportant

C++softwareengineeringconceptusinga"preprocessor

wrapper"inheaderfilestopreventthecodeintheheaderfrom

beingincludedintothesamesourcecodefilemorethanonce.

Sinceaclasscanbedefinedonlyonce,usingsuchpreprocessor

directivespreventsmultiple-definitionerrors.



Figure9.1.Timeclassdefinition.



1//Fig.9.1:Time.h

2//DeclarationofclassTime.

3//MemberfunctionsaredefinedinTime.cpp

4

5//preventmultipleinclusionsofheaderfile

6#ifndefTIME_H

7#defineTIME_H

8

9//Timeclassdefinition

10classTime

11{

12public:

13Time();//constructor

14voidsetTime(int,int,int);//sethour,minuteandsecond

15voidprintUniversal();//printtimeinuniversal-timeformat

16voidprintStandard();//printtimeinstandard-timeformat

17private:

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

19intminute;//0-59

20intsecond;//0-59

21};//endclassTime

22

23#endif



[Page483]



TimeClassDefinition

Theclassdefinition(Fig.9.1)containsprototypes(lines1316)

formemberfunctionsTime,setTime,printUniversaland

printStandard.Theclassincludesprivateintegermembershour,

minuteandsecond(lines1820).ClassTime'sprivatedatamembers

canbeaccessedonlybyitsfourmemberfunctions.Chapter12

introducesathirdaccessspecifier,protected,aswestudy

inheritanceandthepartitplaysinobject-oriented

programming.



GoodProgrammingPractice9.1

Forclarityandreadability,useeachaccessspecifieronly

onceinaclassdefinition.Placepublicmembersfirst,

wheretheyareeasytolocate.



SoftwareEngineeringObservation9.1

Eachelementofaclassshouldhaveprivatevisibility

unlessitcanbeproventhattheelementneedspublic

visibility.Thisisanotherexampleoftheprincipleofleast

privilege.



InFig.9.1,notethattheclassdefinitionisenclosedinthe



followingpreprocessorwrapper(lines57and23):

//preventmultipleinclusionsofheaderfile

#ifndefTIME_H

#defineTIME_H

...

#endif



Whenwebuildlargerprograms,otherdefinitionsand

declarationswillalsobeplacedinheaderfiles.Thepreceding

preprocessorwrapperpreventsthecodebetween#ifndef

(whichmeans"ifnotdefined")and#endiffrombeingincluded

ifthenameTIME_Hhasbeendefined.Iftheheaderhasnotbeen

includedpreviouslyinafile,thenameTIME_Hisdefinedbythe

#definedirectiveandtheheaderfilestatementsareincluded.

Iftheheaderhasbeenincludedpreviously,TIME_Hisdefined

alreadyandtheheaderfileisnotincludedagain.Attemptsto

includeaheaderfilemultipletimes(inadvertently)typically

occurinlargeprogramswithmanyheaderfilesthatmay

themselvesincludeotherheaderfiles.[Note:Thecommonly

usedconventionforthesymbolicconstantnameinthe

preprocessordirectivesissimplytheheaderfilenameinupper

casewiththeunderscorecharacterreplacingtheperiod.]



Error-PreventionTip9.1

Use#ifndef,#defineand#endifpreprocessordirectivesto

formapreprocessorwrapperthatpreventsheaderfiles

frombeingincludedmorethanonceinaprogram.



GoodProgrammingPractice9.2

Usethenameoftheheaderfileinuppercasewiththe

periodreplacedbyanunderscoreinthe#ifndefand

#definepreprocessordirectivesofaheaderfile.



TimeClassMemberFunctions

InFig.9.2,theTimeconstructor(lines1417)initializesthedata

membersto0(i.e.,theuniversal-timeequivalentof12AM).

Thisensuresthattheobjectbeginsinaconsistentstate.Invalid

valuescannotbestoredinthedatamembersofaTimeobject,

becausetheconstructoriscalledwhentheTimeobjectis

created,andallsubsequentattemptsbyaclienttomodifythe

datamembersarescrutinizedbyfunctionsetTime(discussed

shortly).Finally,itisimportanttonotethattheprogrammer

candefineseveraloverloadedconstructorsforaclass.



[Page484]

Figure9.2.Timeclassmember-function

definitions.



1//Fig.9.2:Time.cpp

2//Member-functiondefinitionsforclassTime.

3#include

4usingstd::cout;

5

6#include

7usingstd::setfill;

8usingstd::setw;



9

10#include"Time.h"//includedefinitionofclassTimefromTime.h

11

12//Timeconstructorinitializeseachdatamembertozero.

13//EnsuresallTimeobjectsstartinaconsistentstate.

14Time::Time()

15{

16hour=minute=second=0;

17}//endTimeconstructor

18

19//setnewTimevalueusinguniversaltime;ensurethat

20//thedataremainsconsistentbysettinginvalidvaluestozero

21voidTime::setTime(inth,intm,ints)

22{

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

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

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

26}//endfunctionsetTime

27

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

29voidTime::printUniversal()

30{

31cout<
32<
33}//endfunctionprintUniversal

34

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

36voidTime::printStandard()

37{

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

39<
40<
41}//endfunctionprintStandard



Thedatamembersofaclasscannotbeinitializedwherethey

aredeclaredintheclassbody.Itisstronglyrecommendedthat

thesedatamembersbeinitializedbytheclass'sconstructor(as

thereisnodefaultinitializationforfundamental-typedata

members).DatamemberscanalsobeassignedvaluesbyTime's

setfunctions.[Note:Chapter10demonstratesthatonlya

class'sstaticconstdatamembersofintegralorenumtypescanbe

initializedintheclass'sbody.]



[Page485]



CommonProgrammingError9.1

Attemptingtoinitializeanon-staticdatamemberofa

classexplicitlyintheclassdefinitionisasyntaxerror.



FunctionsetTime(lines2126)isapublicfunctionthatdeclares

threeintparametersandusesthemtosetthetime.A

conditionalexpressiontestseachargumenttodetermine

whetherthevalueisinaspecifiedrange.Forexample,thehour

value(line23)mustbegreaterthanorequalto0andlessthan

24,becausetheuniversal-timeformatrepresentshoursas

integersfrom0to23(e.g.,1PMishour13and11PMishour

23;midnightishour0andnoonishour12).Similarly,both

minuteandsecondvalues(lines24and25)mustbegreaterthan

orequalto0andlessthan60.Anyvaluesoutsidetheseranges

aresettozerotoensurethataTimeobjectalwayscontains

consistentdatathatis,theobject'sdatavaluesarealwayskept

inrange,evenifthevaluesprovidedasargumentstofunction

setTimewereincorrect.Inthisexample,zeroisaconsistent

valueforhour,minuteandsecond.

AvaluepassedtosetTimeisacorrectvalueifitisintheallowed

rangeforthememberitisinitializing.So,anynumberinthe

range023wouldbeacorrectvalueforthehour.Acorrectvalue

isalwaysaconsistentvalue.However,aconsistentvalueisnot

necessarilyacorrectvalue.IfsetTimesetshourto0becausethe

argumentreceivedwasoutofrange,thenhouriscorrectonlyif

thecurrenttimeiscoincidentallymidnight.

FunctionprintUniversal(lines2933ofFig.9.2)takesno

argumentsandoutputsthedateinuniversal-timeformat,

consistingofthreecolon-separatedpairsofdigitsforthehour,

minuteandsecond,respectively.Forexample,ifthetimewere



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

Chapter 9. Classes: A Deeper Look, Part 1

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

×