Tải bản đầy đủ - 0 (trang)
Chapter 11. Programmer-Defined Classes and Objects

Chapter 11. Programmer-Defined Classes and Objects

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

Chapter11.Programmer-DefinedClasses

andObjects

OBJECTIVES

Todefineaclassandinstantiateobjectsinaprogram

Tocodeclassmemberfunctions

Tousethescoperesolutionoperatortodefineaclass

memberfunctionoutsidetheclassdeclaration

Toaccessaclassmemberusingthe"dot"notation

Todifferentiatebetweenaccessorandmutatorfunctions

Tocodeaclassconstructor

Tocodeaclassdestructor

Toassignoneobjecttoanother

Tooverloadclassconstructors

Tousedefaultargumentsinafunction

Tocodeandusefunctiontemplates

Inthelastchapter,weintroducedtheconceptsofobjectsand

classesthroughthestudyoftheC++built-instringclass.In

thischapter,youwilllearnhowtodefineyourownclassesand

instantiateclassobjects.Youwillalsolearn,inthisandthe



followingchapters,howtomanipulateobjectsofyourown

classesinwayssimilartowhatwelearnedhowtodoforstring

classobjects.



[Page476(continued)]



11.1.DeclaringObjectsandClasses

IntheintroductiontoChapter10,wediscussedanobjectorientedviewofanATMsystem.Inthatexample,wespoke

abouttheuserasanobject,theATMasanobject,andyour

savingsaccountasanobject.Yoursavingsaccountwasan

objectintheSavings_Accountclass.Inthissection,weshowhow

todeclaretheSavings_Accountclassandinstantiate

Savings_Accountobjects.Wealsodiscussthevariousissues

surroundingthedeclarationofaclassandclassmembers.

Beforecontinuing,youmightwanttorereadtheintroductory

sectionofChapter10.



[Page477]



11.1.1.DefiningaClass

Considerthefollowingclassdefinition:



classSavings_Account

{

private:

stringid_no;

doublebalance;

doublerate;

public:

Savings_Account(string,double,double);

doubleCalc_Interest();

};

Savings_Account::Savings_Account(stringid,doublebal,double

{

id_no=id;



balance=bal;

rate=rt;

}

doubleSavings_Account::Calc_Interest()

{

returnbalance*rate;

}



Theclassdefinitionbeginswiththekeywordclassfollowedby

thenameoftheclass.Asyousee,wecapitalizethefirstletter

ofthenameofaclass.Althoughitisnotrequiredtocapitalize

thefirstletterofaclassname,itisacommonconventiontodo

so.Followingthenameoftheclassisthedefinitionoftheclass

enclosedinbraces.Notethatyoumustfollowtheclosingbrace

byasemicolon.SeeExperiment1.

Theitemsdeclaredintheclassaretheclassmembers.The

classhasthreedatamembers,orinstancevariables,id_no,

balance,andrate.Thesearecalledinstancevariablesbecause

eachSavings_Accountobjectthatweinstantiatecontainsitsown

copiesofthesethreedatamembers.Thevaluesoftheinstance

variablesforaparticularobjectdeterminethestateofthat

object.TheSavings_Accountclassalsocontainstwomethods,

Savings_Account(),aclassconstructor,andCalc_Interest().Recall

thatclassmethodsdeterminethebehaviorofalltheobjectsof

thatclasseveryobjectintheclasshasthesamebehavior.

Therearetwonewkeywordsintheclassdefinition.Theaccess

specifiersprivateandpublicdeterminethevisibilityoftheclass

members.Classmembersdeclaredaftertheprivatelabelcanbe

accessedonlybythemethodsofthatclass.Thus,id_no,balance,

andrate,beingprivateinstancevariables,areaccessibleonlyto

themethodsSavings_Account()andCalc_Interest().Noother

functionshaveaccesstoid_no,balance,orrate.Thus,ifwe

declareanAccountobjectinmain(),wecannotdirectlyreferto



thatobject'sprivateinstancevariablesbecausemain()isnota

methodofSavings_Account.Therefore,thefollowingstatementin

main()isillegal.SeeExperiment2.



[Page478]

cout<


PrivateclassmembersareC++'swaytoenforcetheprincipleof

informationhiding,whichwediscussedinChapter10.The

thingsthatmakeanobjectwhatitis,theobject'sstate,are

kepthiddenfromtheoutsideworld.Theonlywaytochangea

privateinstancevariableofanobjectisthroughtheuseofthe

class'smethods.Informationhidingtightlycontrolshowwe

mayuseobjects,wecanusethemonlythroughtheclass's

methods.

Allclassmembersthatfollowthelabelpublic,inourexample

Calc_Interest()andSavings_Account(),areaccessibletoall

functions.Bypublicaccessibilitywemeanthatmain(),orany

otherfunctionorclass,canusethepublicmethodstosend

correspondingmessagestotheobjectsofthatclass.(Infact,

sometimesthepublicmethodsofaclassarecalledthepublic

interfaceoftheclass.)However,howthemethodswork,that

is,theactualcodeofthemethods,isnotknownoutsidethe

class.This,therefore,alsoenforcestheprincipleofinformation

hiding.

Whydoweneedtwotypesofaccess?Wedonotwantjust

anyonetobeabletochangetheIDnumber,balance,orinterest

rateofanaccount.Therefore,itmakessensetomakethese

itemsprivate.Similarly,wewantobjects(perhapstheATM)to

beabletorequestthecreationandinitializationofanaccount,

andtosendamessagetoanaccountobjectforittocalculate

interestduetheaccount.Therefore,wemakethemethods



public.

Almostalways,theinstancevariablesofaclassareprivateand

theclassmethodsarepublic.Itispossible,althoughunusual,

tohaveapublicinstancevariable;remember,wewantto

enforceinformationhiding.However,weshallseeinlater

examplesthatitissometimesdesirabletohaveaprivateclass

method.Privateclassmethodsarealsoaccessibletoallother

methodsofthatclass.

Notethatprivateisthedefaultaccessspecifier.Thus,the

followingdeclarationisequivalenttothepreviousclass

declaration.

classAccount

{

stringid_no;//Theseareprivatebydefault

doublebalance;

doublerate;

public:

Savings_Account(string,double,double);

doubleCalc_Interest();

};



Itiscommonpractice,andweshalldoso,tokeepallthepublic

itemstogetherandalltheprivateitemstogether.However,itis

notnecessary.Thefollowingislegal,butnotdesirable.



[Page479]

classSavings_Account

{

private:

stringid_no;



public:

Savings_Account(string,double,double);

private:

doublebalance;

public:

doubleCalc_Interest();

private:

doublerate;

};



Asyoucansee,wedeclarethemethodsCalc_Interest()and

Savings_Account()intheclassdefinition,butdefinethemoutside

theclassdefinition.Itispossibletodefineaclassmethodinside

theclassdefinition.Weshalldosoinafewexampleslaterin

thebook.However,ineithercase,themethodmustbedeclared

insidetheclassdeclaration.



Note11.1DeclaringClassMethods

Allclassmethodsmustbedeclaredinsidetheclass

definition,includingthosemethodsthataredefined

outsidetheclassdeclaration.



11.1.2.ClassMethods

Anymethodthatisdefinedoutsidetheclassdeclarationmust

usethescoperesolutionoperator,::,initsdefinitionheader.

Note11.2describeshowtousethescoperesolutionoperator.



Note11.2TheScopeResolutionOperator



Ifyoudefineaclassmethodoutsidetheclass

definition,youmustusethescoperesolution

operator,::,inthemethoddefinitionheaderas

follows:

return-typeClassName::MethodName(parameter-list)



Readtheoperator::asthepossessive"'s".



Thus,readthedefinitionheaderofCalc_Interest()as

"Savings_Account'sCalc_Interest()."Whyisthescoperesolution

operatornecessary?Therearesituationsinwhichitis

necessarytodeclareseveralclasses.Inthiscase,itispossible

thattwoormoreoftheclasseswillhavemethodswiththe

samename.Suppose,forexample,thatwealsodeclarea

CD_Accountclass,whichalsohasaCalc_Interest()method.Ifthe

Calc_Interest()methodsofthetwoclassesaredefinedinside

theirrespectiveclassdefinitions,therewouldbenoconfusion

aboutwhichmethodisbeingdefined.However,ifthemethods

aredefinedoutsidetheclassdefinitions,aswedidforthe

Calc_Interest()method,thenitisnecessarytospecifytowhich

classeachmethodtheCalc_Interest()methodbelongs.The

definitionSavings_Account::Calc_Interest()wouldbefor

Savings_Account'sCalc_Interest()method,andthedefinition

CD_Account::Calc_Interest()wouldbeforCD_Account'sCalc_Interest()

method.SeeExperiment3.Acommonpracticeistodefine

shortmethods(oneortwostatements)withintheclass

definitionandlongermethodsoutsidetheclassdeclaration.



[Page480]



Itisveryimportanttorememberthatclassmethodshave

accesstoalltheinstancevariablesoftheclass.Thereisno

needtodeclaretheclassinstancevariablesinsideaclass

methodjustusetheinstancevariablesinthemethod.



Note11.3InstanceVariablesInside

Methods

Allinstancevariablesofaclassareaccessibleinside

allmethodsoftheclass.Therefore,youcancodea

classmethodasthoughtheclassinstancevariables

havebeendeclaredinsidethemethoddefinition.



InthedefinitionoftheCalc_Interest()method,wedonotredeclaretheinstancevariables.Themethodsautomaticallyhave

accesstoalltheclass'sinstancevariables.Themethod

computestheinterestearnedbytheaccount,thatis,the

balancemultipliedbytheinterestrate.Therefore,the

statementinthemethodbodyreturnstheproductofthedata

membersbalanceandrate.



11.1.3.TheClassConstructor

Aconstructorisaclassmethodthatautomaticallyexecutes

whenanobjectofthatclassisinstantiated.Thenameofthe

constructormustbethesameasthenameoftheclassandthe

constructorcannothaveareturntype(becauseitalwaysresults

increatingaclassobject).Ifaconstructorisnotexplicitly

declaredintheclassdefinition,bydefault,C++providesthe

defaultconstructor.Thedefaultconstructoronlycreatesthe

objectitdoesnotinitializetheobject'sdatamembers.



Note11.4TheNameofaConstructor

Ifaconstructorisexplicitlydeclaredinaclass

declaration,theconstructormusthavethesame

nameastheclass.Theconstructorcannothavea

returntypeandmustbepublic.



Thescoperesolutionoperatormustbeusedinthedefinitionof

theconstructorbecausethedefinitionisoutsidetheclass

declaration.Notealsothatifwedeclareaconstructorthathas

oneormorearguments(astheSavings_Account()constructorwith

threearguments)thedefaultno-argumentconstructorisno

longeravailabletotheprogram.Inthiscase,everyobjectthat

isdeclaredmustbeinitialized.Therefore,thefollowing

declaration,ifincludedinaprogramthatusestheSavings_Account

class,wouldbeillegal.SeeExperiment4.



[Page481]

Savings_Accountacc1;



Ifthereisneedfortheno-argumentconstructor,youcan,of

course,codeyourown.



Note11.5InitializingObjects

Inaclass,ifyoudeclareaconstructorwithoneor

morearguments,thedefaultno-argument

constructorisnolongeravailabletotheprogram.

Therefore,inthiscase,youmustinitializeevery

objectyoudeclarebyprovidingthepropernumber



ofarguments.Ifnecessary,youcanregainthenoargumentconstructorbycodingityourself.



InsidethedefinitionofSavings_Account()wecanrefertothe

instancevariablesoftheclassasthoughtheyweredeclared

insidethemethoditself.(SeeNote11.3.)Thepurposeofthe

constructoristoinitializeanaccountwithitsbasicdataanID

number,balance,andinterestrate.

Tousetheconstructorinmain(),therefore,wewouldproceedas

follows.

voidmain()

{

intid;

doublebal;

doublert;

cout<<"\nEnterAccountID:";

cin>>id;

cout<<"\nEnterBalance:";

cin>>bal;

cout<<"\nEnterInterestRate:";

cin>>rt;

Savings_Accountacc1(id,bal,rt);

.

.

.



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

Chapter 11. Programmer-Defined Classes and Objects

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

×