C++程序設(shè)計英文課件:Ch3 Introduction to Classes and Objects_第1頁
C++程序設(shè)計英文課件:Ch3 Introduction to Classes and Objects_第2頁
C++程序設(shè)計英文課件:Ch3 Introduction to Classes and Objects_第3頁
C++程序設(shè)計英文課件:Ch3 Introduction to Classes and Objects_第4頁
C++程序設(shè)計英文課件:Ch3 Introduction to Classes and Objects_第5頁
已閱讀5頁,還剩87頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

13IntroductiontoClassesandObjects2OBJECTIVESInthischapteryou’lllearn:Whatclasses,objects,memberfunctionsanddatamembersare.Howtodefineaclassanduseittocreateanobject.Howtodefinememberfunctionsinaclasstoimplementtheclass'sbehaviors.Howtodeclaredatamembersinaclasstoimplementtheclass'sattributes.Howtocallamemberfunctionofanobjecttomakethatmemberfunctionperformitstask.Thedifferencesbetweendatamembersofaclassandlocalvariablesofafunction.Howtouseaconstructortoensurethatanobject'sdataisinitializedwhentheobjectiscreated.Howtoengineeraclasstoseparateitsinterfacefromitsimplementationandencouragereuse.33.1 Introduction3.2 Classes,Objects,MemberFunctionsandDataMembers3.3 OverviewoftheChapterExamples3.4 DefiningaClasswithaMemberFunction3.5 DefiningaMemberFunctionwithaParameter3.6 DataMembers,setFunctionsandgetFunctions3.7 InitializingObjectswithConstructors3.8 PlacingaClassinaSeparateFileforReusability3.9 SeparatingInterfacefromImplementation3.10 ValidatingDatawithsetFunctions3.11 (Optional)SoftwareEngineeringCaseStudy:IdentifyingtheClassesintheATMRequirementsSpecification3.12 Wrap-Up43.1IntroductionProgramsfromChapter2AllstatementswerelocatedinfunctionmainTypicallyProgramswillconsistofFunctionmainandOneormoreclassesEachcontainingdatamembersandmemberfunctions53.2Classes,Objects,MemberFunctionsandDataMembersReviewofclasses:CarexampleFunctionsdescribethemechanismsthatperformatasks,suchasaccelerationHidecomplextasksfromtheuser,justasadrivercanusethepedaltoacceleratewithoutneedingtoknowhowtheaccelerationisperformedClassesmustbedefinedbeforetheycanbeused;acarmustbebuiltbeforeitcanbedrivenManycarobjectscanbecreatedfromthesameclass,manycarscanbebuiltfromsameengineeringdrawing63.2Classes,Objects,MemberFunctionsandDataMembers(Cont.)Reviewofclasses:Carexample(Cont.)Member-functioncallssendmessagestoanobjecttoperformtasks,justlikepressingthegaspedalsendsamessagetothecartoaccelerateObjectsandcarsbothhaveattributes,likecolorandmilesdriven73.3OverviewoftheChapterExamplesSevensimpleexamplesExamplesusedtobuildaGradeBookclassTopicscovered:MemberfunctionsDatamembersClientsofaclassOtherclassesorfunctionsthatcallthememberfunctionsofthisclass’sobjectsSeparatinginterfacefromimplementationDatavalidationEnsuresthatdatainanobjectisinaparticularformatorrange83.4DefiningaClassWithaMemberFunctionClassdefinitionTellscompilerwhatmemberfunctionsanddatamembersbelongtotheclassKeywordclassfollowedbytheclass’snameClassbodyisenclosedinbraces({})SpecifiesdatamembersandmemberfunctionsAccess-specifierpublic:Indicatesthatamemberfunctionordatamemberisaccessibletootherfunctionsandmemberfunctionsofotherclasses9Outlinefig03_01.cpp

(1of1)BeginningofclassdefinitionforclassGradeBookBeginningofclassbodyEndofclassbodyAccessspecifierpublic;makesmembersavailabletothepublicMemberfunctiondisplayMessagereturnsnothingUsedotoperatortocallGradeBook’smemberfunction10CommonProgrammingError3.1Forgettingthesemicolonattheendofaclassdefinitionisasyntaxerror.113.4DefiningaClassWithaMemberFunction(Cont.)MemberfunctiondefinitionReturntypeofafunctionIndicatesthetypeofvaluereturnedbythefunctionwhenitcompletesitstaskvoidindicatesthatthefunctiondoesnotreturnanyvalueFunctionnamemustbeavalididentifierParenthesesafterfunctionnameindicatethatitisafunctionFunctionbodycontainsstatementsthatperformthefunction’staskDelimitedbybraces({})12CommonProgrammingError3.2Returningavaluefromafunctionwhosereturntypehasbeendeclaredvoidisacompilationerror.13CommonProgrammingError3.3Definingafunctioninsideanotherfunctionisasyntaxerror.143.4DefiningaClassWithaMemberFunction(Cont.)UsingaclassAclassisauser-definedtype(orprogrammer-definedtype)CanbeusedtocreateobjectsVariablesoftheclasstypeC++isanextensiblelanguageDotoperator(.)Usedtoaccessanobject’sdatamembersandmemberfunctionsExamplemyGradeBook.displayMessage()CallmemberfunctiondisplayMessageofGradeBookobjectmyGradeBook15Fig.3.2

|UMLclassdiagramindicatingthatclassGradeBookhasapublicdisplayMessageoperation.163.4DefiningaClassWithaMemberFunction(Cont.)UMLclassdiagramArectanglewiththreecompartmentsTopcompartmentcontainsthenameoftheclassMiddlecompartmentcontainstheclass’sattributesBottomcompartmentcontainstheclass’soperationsA(+)infrontofanoperationindicatesitispublic173.5DefiningaMemberFunctionwithaParameterFunctionparameter(s)InformationneededbyafunctiontoperformitstaskFunctionargument(s)Valuessuppliedbyafunctioncallforeachofthefunction’sparametersArgumentvaluesarecopiedintofunctionparametersatexecutiontime183.5DefiningaMemberFunctionwithaParameter(Cont.)Astring

RepresentsastringofcharactersAnobjectofC++StandardLibraryclassstd::stringDefinedinheaderfile<string>LibraryfunctiongetlineUsedtoretrieveinputuntilnewlineisencounteredExamplegetline(cin,nameOfCourse);Inputsalinefromstandardinputintostringobject

nameOfCourse19Outlinefig03_03.cpp

(1of2)IncludestringclassdefinitionMemberfunctionparameterUsethefunctionparameterasavariable20Outlinefig03_03.cpp

(2of2)Passinganargumenttothememberfunction213.5DefiningaMemberFunctionwithaParameter(Cont.)ParameterListsAdditionalinformationneededbyafunctionLocatedinparenthesesfollowingthefunctionnameAfunctionmayhaveanynumberofparametersParametersareseparatedbycommasThenumber,orderandtypesofargumentsinafunctioncallmustmatchthenumber,orderandtypesofparametersinthecalledfunction’sparameterlistModeledinUMLParametername,followedbyacolonandtheparametertypeinthememberfunction’sparentheses22CommonProgrammingError3.44Placingasemicolonaftertherightparenthesisenclosingtheparameterlistofafunctiondefinitionisasyntaxerror.23CommonProgrammingError3.5Definingafunctionparameteragainasalocalvariableinthefunctionisacompilationerror.24GoodProgrammingPractice3.1Toavoidambiguity,donotusethesamenamesfortheargumentspassedtoafunctionandthecorrespondingparametersinthefunctiondefinition.25GoodProgrammingPractice3.2Choosingmeaningfulfunctionnamesandmeaningfulparameternamesmakesprogramsmorereadableandhelpsavoidexcessiveuseofcomments.26Fig.3.4

|UMLclassdiagramindicatingthatclassGradeBookhasadisplayMessageoperationwithacourseNameparameterofUMLtypeString.273.6DataMembers,setFunctionsandgetFunctionsLocalvariablesVariablesdeclaredinafunctiondefinition’sbodyCannotbeusedoutsideofthatfunctionbodyWhenafunctionterminatesThevaluesofitslocalvariablesarelostAttributesExistthroughoutthelifeoftheobjectRepresentedasdatamembersVariablesinaclassdefinitionEachobjectofclassmaintainsitsowncopyofattributes28Outlinefig03_05.cpp

(1of3)setfunctionmodifiesprivatedatagetfunctionaccessesprivatedata29Outlinefig03_05.cpp

(2of3)Usesetandgetfunctions,evenwithintheclassAccessingprivatedataoutsideclassdefinitionprivatemembersaccessibleonlytomemberfunctionsoftheclass30Outlinefig03_05.cpp

(3of3)Modifyingprivatedatafromoutsidetheclassdefinition31GoodProgrammingPractice3.3Placeablanklinebetweenmember-functiondefinitionstoenhanceprogramreadability.323.6DataMembers,setFunctionsandgetFunctions(Cont.)Access-specifierprivate

MakesadatamemberormemberfunctionaccessibleonlytomemberfunctionsoftheclassprivateisthedefaultaccessforclassmembersDatahidingReturningavaluefromafunctionAfunctionthatspecifiesareturntypeotherthanvoidMustreturnavaluetoitscallingfunction33SoftwareEngineeringObservation3.1Asarule,datamembersshouldbedeclaredprivateandmemberfunctionsshouldbedeclaredpublic.(Wewillseethatitisappropriatetodeclarecertainmemberfunctionsprivate,iftheyaretobeaccessedonlybyothermemberfunctionsoftheclass.)34CommonProgrammingError3.6Anattemptbyafunction,whichisnotamemberofaparticularclass(orafriendofthatclass,aswe’llseeinChapter

10),toaccessaprivatememberofthatclassisacompilationerror.35GoodProgrammingPractice3.4Despitethefactthatthepublicandprivateaccessspecifiersmayberepeatedandintermixed,listallthepublicmembersofaclassfirstinonegroupandthenlistalltheprivatemembersinanothergroup.Thisfocusestheclient’sattentionontheclass’spublicinterface,ratherthanontheclass’simplementation.36GoodProgrammingPractice3.5Ifyouchoosetolisttheprivatemembersfirstinaclassdefinition,explicitlyusetheprivateaccessspecifierdespitethefactthatprivateisassumedbydefault.Thisimprovesprogramclarity.37SoftwareEngineeringObservation3.2We’lllearninChapter

10,Classes:Part2,thatfunctionsandclassesdeclaredbyaclasstobefriendsofthatclasscanaccesstheprivatemembersoftheclass.38Error-PreventionTip3.1Makingthedatamembersofaclassprivateandthememberfunctionsoftheclasspublicfacilitatesdebuggingbecauseproblemswithdatamanipulationsarelocalizedtoeithertheclass’smemberfunctionsorthefriendsoftheclass.39CommonProgrammingError3.7Forgettingtoreturnavaluefromafunctionthatissupposedtoreturnavalueisacompilationerror.403.6DataMembers,setFunctionsandgetFunctions(Cont.)SoftwareengineeringwithsetandgetfunctionspublicmemberfunctionsthatallowclientsofaclasstosetorgetthevaluesofprivatedatamemberssetfunctionsaresometimescalledmutatorsandgetfunctionsaresometimescalledaccessorsUsingsetandgetfunctionsallowsthecreatoroftheclasstocontrolhowclientsaccessprivatedataShouldalsobeusedbyothermemberfunctionsofthesameclass41GoodProgrammingPractice3.6Alwaystrytolocalizetheeffectsofchangestoaclass’sdatamembersbyaccessingandmanipulatingthedatamembersthroughtheirgetandsetfunctions.Changestothenameofadatamemberorthedatatypeusedtostoreadatamemberthenaffectonlythecorrespondinggetandsetfunctions,butnotthecallersofthosefunctions.42SoftwareEngineeringObservation3.3Itisimportanttowriteprogramsthatareunderstandableandeasytomaintain.Changeistheruleratherthantheexception.Programmersshouldanticipatethattheircodewillbemodified.43SoftwareEngineeringObservation3.4Theclassdesignerneednotprovidesetorgetfunctionsforeachprivatedataitem;thesecapabilitiesshouldbeprovidedonlywhenappropriate.Ifaserviceisusefultotheclientcode,thatserviceshouldtypicallybeprovidedintheclass’spublicinterface.443.6DataMembers,setFunctionsandgetFunctions(Cont.)UMLdiagramIndicatingthereturntypeofanoperationPlaceacolonandthereturntypeaftertheparenthesesfollowingtheoperationnameMinussignusedtoindicateprivatemembers45Fig.3.6

|UMLclassdiagramforclassGradeBookwithaprivatecourseNameattributeandpublicoperationssetCourseName,getCourseNameanddisplayMessage.

463.7InitializingObjectswithConstructorsConstructorsFunctionsusedtoinitializeanobject’sdatawhenitiscreatedCallmadeimplicitlywhenobjectiscreatedMustbedefinedwiththesamenameastheclassCannotreturnvaluesNotevenvoidDefaultconstructorhasnoparametersThecompilerwillprovideonewhenaclassdoesnotexplicitlyincludeaconstructorCompiler’sdefaultconstructoronlycallsconstructorsofdatamembersthatareobjectsofclasses47Outlinefig03_07.cpp

(1of3)ConstructorhassamenameasclassandnoreturntypeInitializedatamember48Outlinefig03_07.cpp

(2of3)49Outlinefig03_07.cpp

(3of3)Creatingobjectsimplicitlycallstheconstructor50Error-PreventionTip3.2Unlessnoinitializationofyourclass’sdatamembersisnecessary(almostnever),provideaconstructortoensurethatyourclass’sdatamembersareinitializedwithmeaningfulvalueswheneachnewobjectofyourclassiscreated.51SoftwareEngineeringObservation3.5Datamemberscanbeinitializedinaconstructoroftheclassortheirvaluesmaybesetlateraftertheobjectiscreated.However,itisagoodsoftwareengineeringpracticetoensurethatanobjectisfullyinitializedbeforetheclientcodeinvokestheobject’smemberfunctions.Ingeneral,youshouldnotrelyontheclientcodetoensurethatanobjectgetsinitializedproperly.523.7InitializingObjectswithConstructors(Cont.)ConstructorsinaUMLclassdiagramAppearinthirdcompartment,withoperationsTodistinguishaconstructorfromaclass’soperationsUMLplacestheword“constructor”betweenguillemetsbeforetheconstructor’sname<<constructor>>Usuallyplacedbeforeotheroperations53Fig.3.8

|UMLclassdiagramindicatingthatclassGradeBookhasaconstructorwithanameparameterofUMLtypeString.543.8PlacingaClassinaSeparateFileforReusability.cppfileisknownasasource-codefileHeaderfilesSeparatefilesinwhichclassdefinitionsareplacedAllowcompilertorecognizetheclasseswhenusedelsewhereGenerallyhave.hfilenameextensionsDriverfilesProgramusedtotestsoftware(suchasclasses)Containsamainfunctionsoitcanbeexecuted55Outlinefig03_09.cpp

(1of2)Classdefinitionisinaheaderfile56Outlinefig03_09.cpp

(2of2)57Outlinefig03_10.cpp

(1of1)Includingtheheaderfilecausestheclassdefinitiontobecopiedintothefile583.8PlacingaClassinaSeparateFileforReusability(Cont.)

#includepreprocessordirectiveUsedtoincludeheaderfilesInstructsC++preprocessortoreplacedirectivewithacopyofthecontentsofthespecifiedfileQuotesindicateuser-definedheaderfilesPreprocessorfirstlooksincurrentdirectoryIfthefileisnotfound,looksinC++StandardLibrarydirectoryAnglebracketsindicateC++StandardLibraryPreprocessorlooksonlyinC++StandardLibrarydirectory593.8PlacingaClassinaSeparateFileforReusability(Cont.)CreatingobjectsCompilermustknowsizeofobjectC++objectstypicallycontainonlydatamembersCompilercreatesonecopyofclass’smemberfunctionsThiscopyissharedamongalltheclass’sobjects60Error-PreventionTip3.3Toensurethatthepreprocessorcanlocateheaderfilescorrectly,#includepreprocessordirectivesshouldplacethenamesofuser-definedheaderfilesinquotes(e.g.,"GradeBook.h")andplacethenamesofC++StandardLibraryheaderfilesinanglebrackets(e.g.,<iostream>).613.9SeparatingInterfacefromImplementationInterfaceDescribeswhatservicesaclass’sclientscanuseandhowtorequestthoseservicesButdoesnotrevealhowtheclasscarriesouttheservicesAclassdefinitionthatlistsonlymemberfunctionnames,returntypesandparametertypesFunctionprototypesAclass’sinterfaceconsistsoftheclass’spublicmemberfunctions(services)SeparatinginterfacefromimplementationClientcodeshouldnotbreakiftheimplementationchanges,aslongastheinterfacestaysthesame623.9SeparatingInterfacefromImplementation(Cont.)Separatinginterfacefromimplementation(Cont.)Definememberfunctionsoutsidetheclassdefinition,inaseparatesource-codefileInsource-codefileforaclassUsebinaryscoperesolutionoperator(::)to“tie”eachmemberfunctiontotheclassdefinitionImplementationdetailsarehiddenClientcodedoesnotneedtoknowtheimplementationIntheheaderfileforaclassFunctionprototypesdescribetheclass’spublicinterface63Outlinefig03_11.cpp

(1of1)Interfacecontainsdatamembersandmemberfunctionprototypes64CommonProgrammingError3.8Forgettingthesemicolonattheendofafunctionprototypeisasyntaxerror.65GoodProgrammingPractice3.7Althoughparameternamesinfunctionprototypesareoptional(theyareignoredbythecompiler),manyprogrammersusethesenamesfordocumentationpurposes.66Error-PreventionTip3.4Parameternamesinafunctionprototype(which,again,areignoredbythecompiler)canbemisleadingifwrongorconfusingnamesareused.Forthisreason,manyprogrammerscreatefunctionprototypesbycopyingthefirstlineofthecorrespondingfunctiondefinitions(whenthesourcecodeforthefunctionsisavailable),thenappendingasemicolontotheendofeachprototype.67CommonProgrammingError3.9Whendefiningaclass’smemberfunctionsoutsidethatclass,omittingtheclassnameandbinaryscoperesolutionoperator(::)precedingthefunctionnamescausescompilationerrors.

68Outlinefig03_12.cpp

(1of2)Binaryscoperesolutionoperator“ties”afunctiontoitsclassGradeBookimplementationisplacedinaseparatesource-codefileIncludetheheaderfiletoaccesstheclassnameGradeBook69Outlinefig03_12.cpp

(2of2)70Outlinefig03_13.cpp

(1of1)713.9SeparatingInterfacefromImplementation(Cont.)TheCompilationandLinkingProcessSource-codefileiscompiledtocreatetheclass’sobjectcode(source-codefilemust#includeheaderfile)ClassimplementationprogrammeronlyneedstoprovideheaderfileandobjectcodetoclientClientmust#includeheaderfileintheirowncodeSocompilercanensurethatthemainfunctioncreatesandmanipulatesobjectsoftheclasscorrectlyTocreateexecutableapplicationObjectcodeforclientcodemustbelinkedwiththeobjectcodefortheclassandtheobjectcodeforanyC++StandardLibraryobjectcodeusedintheapplication72Fig.3.14|Compilationandlinkingprocessthatproducesanexecutableapplication.733.10ValidatingDatawithsetFunctionssetfunctionscanvalidatedataKnownasvaliditycheckingKeepsobjectinaconsistentstateThedatamembercontainsavalidvalueCanreturnvaluesindicatingthatattemptsweremadetoassigninvaliddatastringmemberfunctionslengthreturnsthenumberofcharactersinthestringSubstrreturnsspecifiedsubstringwithinthestring74Outlinefig03_15.cpp

(1of1)75Outlinefig03_16.cpp

(1of2)setfunctionsperformvaliditycheckingtokeepcourseNameinaconsistentstateConstructorcallssetfunctiontoperformvaliditychecking76Outlinefig03_16.cpp

(2of2)77Outlinefig03_17.cpp

(1of2)Constructorwillcallsetfunctiontoperformvaliditychecking78Outlinefig03_17.cpp

(2of2)Callsetfunctiontoperformvaliditychecking79SoftwareEngineeringObservation3.6Makingdatamembersprivateandcontrollingaccess,especiallywriteaccess,tothosedatamembersthroughpublicmemberfunctionshelpsensuredataintegrity.80Error-PreventionTip3.5Thebenefitsofdataintegrityarenotautomaticsimplybecausedatamembersaremadeprivate—theprogrammermustprovideappropriatevaliditycheckingandreporttheer

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論