Tải bản đầy đủ - 0 (trang)
Chapter 3. Introduction to Classes and Objects

Chapter 3. Introduction to Classes and Objects

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

Chapter3.IntroductiontoClassesand

Objects

Youwillseesomethingnew.Twothings.AndIcall

themThingOneandThingTwo.

Dr.TheodorSeussGeisel

Nothingcanhavevaluewithoutbeinganobjectof

utility.

KarlMarx

Yourpublicservantsserveyouright.

AdlaiE.Stevenson

Knowinghowtoansweronewhospeaks,Toreplyto

onewhosendsamessage.

Amenemope

OBJECTIVES

Inthischapteryouwilllearn:

Whatclasses,objects,memberfunctionsanddatamembers

are.

Howtodefineaclassanduseittocreateanobject.

Howtodefinememberfunctionsinaclasstoimplementthe

class'sbehaviors.



Howtodeclaredatamembersinaclasstoimplementthe

class'sattributes.

Howtocallamemberfunctionofanobjecttomakethat

memberfunctionperformitstask.

Thedifferencesbetweendatamembersofaclassandlocal

variablesofafunction.

Howtouseaconstructortoensurethatanobject'sdatais

initializedwhentheobjectiscreated.

Howtoengineeraclasstoseparateitsinterfacefromits

implementationandencouragereuse.



[Page75]

Outline

3.1Introduction

3.2Classes,Objects,MemberFunctionsandDataMembers

3.3OverviewoftheChapterExamples

3.4DefiningaClasswithaMemberFunction

3.5DefiningaMemberFunctionwithaParameter

3.6DataMembers,setFunctionsandgetFunctions

3.7InitializingObjectswithConstructors

3.8PlacingaClassinaSeparateFileforReusability

3.9SeparatingInterfacefromImplementation



3.10ValidatingDatawithsetFunctions

3.11(Optional)SoftwareEngineeringCaseStudy:Identifying

theClassesintheATMRequirementsDocument

3.12Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page75(continued)]



3.1.Introduction

InChapter2,youcreatedsimpleprogramsthatdisplayed

messagestotheuser,obtainedinformationfromtheuser,

performedcalculationsandmadedecisions.Inthischapter,you

willbeginwritingprogramsthatemploythebasicconceptsof

object-orientedprogrammingthatweintroducedinSection

1.17.OnecommonfeatureofeveryprograminChapter2was

thatallthestatementsthatperformedtaskswerelocatedin

functionmain.Typically,theprogramsyoudevelopinthisbook

willconsistoffunctionmainandoneormoreclasses,each

containingdatamembersandmemberfunctions.Ifyoubecome

partofadevelopmentteaminindustry,youmightworkon

softwaresystemsthatcontainhundreds,oreventhousands,of

classes.Inthischapter,wedevelopasimple,well-engineered

frameworkfororganizingobject-orientedprogramsinC++.

First,wemotivatethenotionofclasseswithareal-world

example.Thenwepresentacarefullypacedsequenceofseven

completeworkingprogramstodemonstratecreatingandusing

yourownclasses.Theseexamplesbeginourintegratedcase

studyondevelopingagrade-bookclassthatinstructorscanuse

tomaintainstudenttestscores.Thiscasestudyisenhanced

overthenextseveralchapters,culminatingwiththeversion

presentedinChapter7,ArraysandVectors.



[Page75(continued)]



3.2.Classes,Objects,MemberFunctionsand

DataMembers

Let'sbeginwithasimpleanalogytohelpyoureinforceyour

understandingfromSection1.17ofclassesandtheircontents.

Supposeyouwanttodriveacarandmakeitgofasterby

pressingdownonitsacceleratorpedal.Whatmusthappen

beforeyoucandothis?Well,beforeyoucandriveacar,

someonehastodesignitandbuildit.Acartypicallybeginsas

engineeringdrawings,similartotheblueprintsusedtodesigna

house.Thesedrawingsincludethedesignforanaccelerator

pedalthatthedriverwillusetomakethecargofaster.Ina

sense,thepedal"hides"thecomplexmechanismsthatactually

makethecargofaster,justasthebrakepedal"hides"the

mechanismsthatslowthecar,thesteeringwheel"hides"the

mechanismsthatturnthecarandsoon.Thisenablespeople

withlittleornoknowledgeofhowcarsareengineeredtodrive

acareasily,simplybyusingtheacceleratorpedal,thebrake

pedal,thesteeringwheel,thetransmissionshiftingmechanism

andothersuchsimpleanduser-friendly"interfaces"tothecar's

complexinternalmechanisms.



[Page76]

Unfortunately,youcannotdrivetheengineeringdrawingsofa

carbeforeyoucandriveacar,itmustbebuiltfromthe

engineeringdrawingsthatdescribeit.Acompletedcarwillhave

anactualacceleratorpedaltomakethecargofaster.Buteven

that'snotenoughthecarwillnotaccelerateonitsown,sothe

drivermustpresstheacceleratorpedaltotellthecartogo

faster.

Nowlet'suseourcarexampletointroducethekeyobjectorientedprogrammingconceptsofthissection.Performinga



taskinaprogramrequiresafunction(suchasmain,asdescribed

inChapter2).Thefunctiondescribesthemechanismsthat

actuallyperformitstasks.Thefunctionhidesfromitsuserthe

complextasksthatitperforms,justastheacceleratorpedalof

acarhidesfromthedriverthecomplexmechanismsofmaking

thecargofaster.InC++,webeginbycreatingaprogramunit

calledaclasstohouseafunction,justasacar'sengineering

drawingshousethedesignofanacceleratorpedal.Recallfrom

Section1.17thatafunctionbelongingtoaclassiscalleda

memberfunction.Inaclass,youprovideoneormoremember

functionsthataredesignedtoperformtheclass'stasks.For

example,aclassthatrepresentsabankaccountmightcontain

onememberfunctiontodepositmoneyintotheaccount,

anothertowithdrawmoneyfromtheaccountandathirdto

inquirewhatthecurrentaccountbalanceis.

Justasyoucannotdriveanengineeringdrawingofacar,you

cannot"drive"aclass.Justassomeonehastobuildacarfrom

itsengineeringdrawingsbeforeyoucanactuallydrivethecar,

youmustcreateanobjectofaclassbeforeyoucangeta

programtoperformthetaskstheclassdescribes.Thatisone

reasonC++isknownasanobject-orientedprogramming

language.Notealsothatjustasmanycarscanbebuiltfrom

thesameengineeringdrawing,manyobjectscanbebuiltfrom

thesameclass.

Whenyoudriveacar,pressingitsgaspedalsendsamessage

tothecartoperformataskthatis,makethecargofaster.

Similarly,yousendmessagestoanobjecteachmessageis

knownasamember-functioncallandtellsamember

functionoftheobjecttoperformitstask.Thisisoftencalled

requestingaservicefromanobject.

Thusfar,wehaveusedthecaranalogytointroduceclasses,

objectsandmemberfunctions.Inadditiontothecapabilitiesa

carprovides,italsohasmanyattributes,suchasitscolor,the

numberofdoors,theamountofgasinitstank,itscurrent

speedanditstotalmilesdriven(i.e.,itsodometerreading).



Likethecar'scapabilities,theseattributesarerepresentedas

partofacar'sdesigninitsengineeringdiagrams.Asyoudrive

acar,theseattributesarealwaysassociatedwiththecar.Every

carmaintainsitsownattributes.Forexample,eachcarknows

howmuchgasisinitsowngastank,butnothowmuchisin

thetanksofothercars.Similarly,anobjecthasattributesthat

arecarriedwiththeobjectasitisusedinaprogram.These

attributesarespecifiedaspartoftheobject'sclass.For

example,abankaccountobjecthasabalanceattributethat

representstheamountofmoneyintheaccount.Eachbank

accountobjectknowsthebalanceintheaccountitrepresents,

butnotthebalancesoftheotheraccountsinthebank.

Attributesarespecifiedbytheclass'sdatamembers.







[Page77]



3.3.OverviewoftheChapterExamples

Theremainderofthischapterpresentssevensimpleexamples

thatdemonstratetheconceptsweintroducedinthecontextof

thecaranalogy.Theseexamples,summarizedbelow,

incrementallybuildaGradeBookclasstodemonstratethese

concepts:

1. ThefirstexamplepresentsaGradeBookclasswithone

memberfunctionthatsimplydisplaysawelcomemessage

whenitiscalled.Wethenshowhowtocreateanobjectof

thatclassandcallthememberfunctionsothatitdisplays

thewelcomemessage.

2. Thesecondexamplemodifiesthefirstbyallowingthe

memberfunctiontoreceiveacoursenameasaso-called

argument.Then,thememberfunctiondisplaysthecourse

nameaspartofthewelcomemessage.

3. Thethirdexampleshowshowtostorethecoursenameina

GradeBookobject.Forthisversionoftheclass,wealsoshow

howtousememberfunctionstosetthecoursenameinthe

objectandgetthecoursenamefromtheobject.

4. Thefourthexampledemonstrateshowthedataina

GradeBookobjectcanbeinitializedwhentheobjectis

createdtheinitializationisperformedbyaspecialmember

functioncalledtheclass'sconstructor.Thisexamplealso

demonstratesthateachGradeBookobjectmaintainsitsown

coursenamedatamember.

5. Thefifthexamplemodifiesthefourthbydemonstratinghow

toplaceclassGradeBookintoaseparatefiletoenable

softwarereusability.



6. Thesixthexamplemodifiesthefifthbydemonstratingthe

goodsoftware-engineeringprincipleofseparatingthe

interfaceoftheclassfromitsimplementation.Thismakes

theclasseasiertomodifywithoutaffectinganyclientsof

theclass'sobjectsthatis,anyclassesorfunctionsthat

callthememberfunctionsoftheclass'sobjectsfrom

outsidetheobjects.

7. ThelastexampleenhancesclassGradeBookbyintroducing

datavalidation,whichensuresthatdatainanobject

adherestoaparticularformatorisinapropervaluerange.

Forexample,aDateobjectwouldrequireamonthvaluein

therange112.InthisGradeBookexample,themember

functionthatsetsthecoursenameforaGradeBookobject

ensuresthatthecoursenameis25charactersorfewer.If

not,thememberfunctionusesonlythefirst25characters

ofthecoursenameanddisplaysawarningmessage.

NotethattheGradeBookexamplesinthischapterdonotactually

processorstoregrades.Webeginprocessinggradeswithclass

GradeBookinChapter4andwestoregradesinaGradeBookobject

inChapter7,ArraysandVectors.



[Page77(continued)]



3.4.DefiningaClasswithaMemberFunction

Webeginwithanexample(Fig.3.1)thatconsistsofclass

GradeBook,whichrepresentsagradebookthataninstructorcan

usetomaintainstudenttestscores,andamainfunction(lines

2025)thatcreatesaGradeBookobject.Thisisthefirstinaseries

ofgraduatedexamplesleadinguptoafullyfunctionalGradeBook

classinChapter7,ArraysandVectors.Functionmainusesthis

objectanditsmemberfunctiontodisplayamessageonthe

screenwelcomingtheinstructortothegrade-bookprogram.



[Page78]

Figure3.1.DefiningclassGradeBookwitha

memberfunction,creatingaGradeBookobjectand

callingitsmemberfunction.



1//Fig.3.1:fig03_01.cpp

2//DefineclassGradeBookwithamemberfunctiondisplayMessage;

3//CreateaGradeBookobjectandcallitsdisplayMessagefunction.

4#include

5usingstd::cout;

6usingstd::endl;

7

8//GradeBookclassdefinition

9classGradeBook

10{

11public:

12//functionthatdisplaysawelcomemessagetotheGradeBookuser

13voiddisplayMessage()

14{

15cout<<"WelcometotheGradeBook!"<
16}//endfunctiondisplayMessage

17};//endclassGradeBook

18

19//functionmainbeginsprogramexecution

20intmain()

21{



22GradeBookmyGradeBook;//createaGradeBookobjectnamedmyGradeBook

23myGradeBook.displayMessage();//callobject'sdisplayMessagefunction

24return0;//indicatesuccessfultermination

25}//endmain



WelcometotheGradeBook!



Firstwedescribehowtodefineaclassandamemberfunction.

Thenweexplainhowanobjectiscreatedandhowtocalla

memberfunctionofanobject.Thefirstfewexamplescontain

functionmainandtheGradeBookclassitusesinthesamefile.

Laterinthechapter,weintroducemoresophisticatedwaysto

structureyourprogramstoachievebettersoftwareengineering.



ClassGradeBook

Beforefunctionmain(lines2025)cancreateanobjectofclass

GradeBook,wemusttellthecompilerwhatmemberfunctionsand

datamembersbelongtotheclass.Thisisknownasdefininga

class.TheGradeBookclassdefinition(lines917)containsa

memberfunctioncalleddisplayMessage(lines1316)thatdisplays

amessageonthescreen(line15).Recallthataclassislikea

blueprintsoweneedtomakeanobjectofclassGradeBook(line

22)andcallitsdisplayMessagememberfunction(line23)toget

line15toexecuteanddisplaythewelcomemessage.We'llsoon

explainlines2223indetail.

Theclassdefinitionbeginsatline9withthekeywordclass

followedbytheclassnameGradeBook.Byconvention,thename

ofauser-definedclassbeginswithacapitalletter,andfor



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

Chapter 3. Introduction to Classes and Objects

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

×