




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
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)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年三片式球閥項目發(fā)展計劃
- 2025年度汽車銷售市場調(diào)研與分析合同
- 2025版商業(yè)綜合體電梯清潔維護協(xié)議
- 2022年江蘇高考英語真題及答案-2
- 2025年度健康食堂牛羊肉綠色采購配送協(xié)議4篇
- 2025年度足療行業(yè)市場調(diào)研分析合同
- 2025年全自動潷水器合作協(xié)議書
- 幼兒園節(jié)奏感與韻律教育方案計劃
- 班級活動與團隊合作訓練計劃
- 跨學科合作項目的設計與實踐計劃
- 二零二五年度海外市場拓展合作協(xié)議4篇
- 北京市朝陽區(qū)2024-2025學年七年級上學期期末考試數(shù)學試卷(含答案)
- 2025年春新外研版(三起)英語三年級下冊課件 Unit4第2課時Speedup
- 急性呼吸窘迫綜合征的護理課件(演示)
- 2025山東能源集團中級人才庫選拔高頻重點提升(共500題)附帶答案詳解
- 2025中國鐵塔集團安徽分公司招聘29人高頻重點提升(共500題)附帶答案詳解
- 2025年河北省農(nóng)村信用社招聘歷年高頻重點提升(共500題)附帶答案詳解
- 人教版五年級下冊信息技術全冊教案
- 手術室植入物的管理
- 電力供電系統(tǒng)試驗調(diào)試和聯(lián)調(diào)方法
- 天津市紅橋區(qū)2023-2024學年高二上學期期末考試化學試題(含答案)
評論
0/150
提交評論