C++程序设计英文课件:Ch3 Introduction to Classes and Objects_第1页
C++程序设计英文课件:Ch3 Introduction to Classes and Objects_第2页
C++程序设计英文课件:Ch3 Introduction to Classes and Objects_第3页
C++程序设计英文课件:Ch3 Introduction to Classes and Objects_第4页
C++程序设计英文课件:Ch3 Introduction to Classes and Objects_第5页
已阅读5页,还剩87页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论