




已阅读5页,还剩90页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter10,DefiningClasses,Overview,10.1Structures10.2Classes10.3AbstractDataTypes10.4IntroductiontoInheritance,Slide10-3,10.1,Structures,WhatIsaClass?,AclassisadatatypewhosevariablesareobjectsSomepre-defineddatatypesyouhaveusedareintcharApre-definedclassyouhaveusedisifstreamYoucandefineyourownclassesaswell,Slide10-5,ClassDefinitions,AclassdefinitionincludesAdescriptionofthekindsofvaluesthevariablecanholdAdescriptionofthememberfunctionsWewillstartbydefiningstructuresasafirststeptowarddefiningclasses,Slide10-6,Structures,AstructurecanbeviewedasanobjectContainsnomemberfunctions(Thestructuresusedherehavenomemberfunctions)ContainsmultiplevaluesofpossiblydifferenttypesThemultiplevaluesarelogicallyrelatedasasingleitemExample:AbankCertificateofDeposit(CD)hasthefollowingvalues:abalanceaninterestrateaterm(monthstomaturity),Slide10-7,TheCDDefinition,TheCertificateofDepositstructurecanbedefinedasstructCDAccountdoublebalance;doubleinterest_rate;intterm;/monthstomaturity;KeywordstructbeginsastructuredefinitionCDAccountisthestructuretagorthestructurestypeMembernamesareidentifiersdeclaredinthebraces,Slide10-8,UsingtheStructure,StructuredefinitionisgenerallyplacedoutsideanyfunctiondefinitionThismakesthestructuretypeavailabletoallcodethatfollowsthestructuredefinitionTodeclaretwovariablesoftypeCDAccount:CDAccountmy_account,your_account;My_accountandyour_accountcontaindistinctmembervariablesbalance,interest_rate,andterm,Slide10-9,TheStructureValue,TheStructureValueConsistsofthevaluesofthemembervariablesThevalueofanobjectoftypeCDAccountConsistsofthevaluesofthemembervariablesbalanceinterest_rateterm,Slide10-10,SpecifyingMemberVariables,MembervariablesarespecifictothestructurevariableinwhichtheyaredeclaredSyntaxtospecifyamembervariable:Structure_Variable_Name.Member_Variable_NameGiventhedeclaration:CDAccountmy_account,your_account;Usethedotoperatortospecifyamembervariablemy_account.balancemy_erest_ratemy_account.term,Slide10-11,UsingMemberVariables,Membervariablescanbeusedjustasanyothervariableofthesametypemy_account.balance=1000;your_account.balance=2500;Noticethatmy_account.balanceandyour_account.balancearedifferentvariables!my_account.balance=my_account.balance+interest;,Slide10-12,Display10.1(1),Display10.1(2),Display10.2,DuplicateNames,Membervariablenamesduplicatedbetweenstructuretypesarenotaproblem.super_grow.quantityandapples.quantityaredifferentvariablesstoredindifferentlocations,Slide10-13,structFertilizerStockdoublequantity;doublenitrogen_content;FertilizerStocksuper_grow;,structCropYieldintquantity;doublesize;CropYieldapples;,StructuresasArguments,StructurescanbeargumentsinfunctioncallsTheformalparametercanbecall-by-valueTheformalparametercanbecall-by-referenceExample:voidget_data(CDAccountUsesthestructuretypeCDAccountwesawearlierasthetypeforacall-by-referenceparameter,Slide10-14,StructuresasReturnTypes,StructurescanbethetypeofavaluereturnedbyafunctionExample:CDAccountshrink_wrap(doublethe_balance,doublethe_rate,intthe_term)CDAccounttemp;temp.balance=the_balance;erest_rate=the_rate;temp.term=the_term;returntemp;,Slide10-15,UsingFunctionshrink_wrap,shrink_wrapbuildsacompletestructurevalueintemp,whichisreturnedbythefunctionWecanuseshrink_wraptogiveavariableoftypeCDAccountavalueinthisway:CDAccountnew_account;new_account=shrink_wrap(1000.00,5.1,11);,Slide10-16,AssignmentandStructures,TheassignmentoperatorcanbeusedtoassignvaluestostructuretypesUsingtheCDAccountstructureagain:CDAccountmy_account,your_account;my_account.balance=1000.00;my_erest_rate=5.1;my_account.term=12;your_account=my_account;Assignsallmembervariablesinyour_accountthecorrespondingvaluesinmy_account,Slide10-17,HierarchicalStructures,StructurescancontainmembervariablesthatarealsostructuresstructPersonInfocontainsaDatestructure,Slide10-18,structDateintmonth;intday;intyear;,structPersonInfodoubleheight;intweight;Datebirthday;,UsingPersonInfo,AvariableoftypePersonInfoisdeclaredbyPersonInfoperson1;Todisplaythebirthyearofperson1,firstaccessthebirthdaymemberofperson1coutperson1.birthdayButwewanttheyear,sowenowspecifytheyearmemberofthebirthdaymembercoutperson1.birthday.year;,Slide10-19,InitializingClasses,AstructurecanbeinitializedwhendeclaredExample:structDateintmonth;intday;intyear;CanbeinitializedinthiswayDatedue_date=12,31,2004;,Slide10-20,Section10.1Conclusion,CanyouWriteadefinitionforastructuretypeforrecordsconsistingofapersonswagerate,accruedvacation(inwholedays),andstatus(hourlyorsalaried).RepresentthestatusasoneofthetwocharactervaluesHandS.CallthetypeEmployeeRecord.,Slide10-21,10.2,Classes,Classes,AclassisadatatypewhosevariablesareobjectsThedefinitionofaclassincludesDescriptionofthekindsofvaluesofthemembervariablesDescriptionofthememberfunctionsAclassdescriptionissomewhatlikeastructuredefinitionplusthemembervariables,Slide10-23,AClassExample,TocreateanewtypenamedDayOfYearasaclassdefinitionDecideonthevaluestorepresentThisexamplesvaluesaredatessuchasJuly4usinganintegerforthenumberofthemonthMembervariablemonthisanint(Jan=1,Feb=2,etc.)MembervariabledayisanintDecideonthememberfunctionsneededWeusejustonememberfunctionnamedoutput,Slide10-24,ClassDayOfYearDefinition,classDayOfYearpublic:voidoutput();intmonth;intday;,Slide10-25,MemberFunctionDeclaration,DefiningaMemberFunction,MemberfunctionsaredeclaredintheclassdeclarationMemberfunctiondefinitionsidentifytheclassinwhichthefunctionisamembervoidDayOfYear:output()cout“month=“month“,day=“dayendl;,Slide10-26,MemberFunctionDefinition,Memberfunctiondefinitionsyntax:Returned_TypeClass_Name:Function_Name(Parameter_List)FunctionBodyStatementsExample:voidDayOfYear:output()cout“month=“month“,day=“daytoday.monthwillnolongerworkbecausewenowhavethreecharactervariablestoreadif(today.month=birthday.month)willnolongerworktocomparemonthsThememberfunction“output”nolongerworks,Slide10-32,IdealClassDefinitions,ChangingtheimplementationofDayOfYearrequireschangestotheprogramthatusesDayOfYearAnidealclassdefinitionofDayOfYearcouldbechangedwithoutrequiringchangestotheprogramthatusesDayOfYear,Slide10-33,FixingDayOfYear,TofixDayOfYearWeneedtoaddmemberfunctionstousewhenchangingoraccessingthemembervariablesIftheprogramneverdirectlyreferencesthemembervariables,changinghowthevariablesarestoredwillnotrequirechangingtheprogramWeneedtobesurethattheprogramdoesnoteverdirectlyreferencethemembervariables,Slide10-34,PublicOrPrivate?,C+helpsusrestricttheprogramfromdirectlyreferencingmembervariablesprivatemembersofaclasscanonlybereferencedwithinthedefinitionsofmemberfunctionsIftheprogramtriestoaccessaprivatemember,thecompilergivesanerrormessagePrivatememberscanbevariablesorfunctions,Slide10-35,PrivateVariables,PrivatevariablescannotbeaccesseddirectlybytheprogramChangingtheirvaluesrequirestheuseofpublicmemberfunctionsoftheclassTosettheprivatemonthanddayvariablesinanewDayOfYearclassuseamemberfunctionsuchasvoidDayOfYear:set(intnew_month,intnew_day)month=new_month;day=new_day;,Slide10-36,PublicorPrivateMembers,ThekeywordprivateidentifiesthemembersofaclassthatcanbeaccessedonlybymemberfunctionsoftheclassMembersthatfollowthekeywordprivateareprivatemembersoftheclassThekeywordpublicidentifiesthemembersofaclassthatcanbeaccessedfromoutsidetheclassMembersthatfollowthekeywordpublicarepublicmembersoftheclass,Slide10-37,ANewDayOfYear,ThenewDayOfYearclassdemonstratedinDisplay10.4UsesallprivatemembervariablesUsesmemberfunctionstodoallmanipulationoftheprivatemembervariablesMembervariablesandmemberfunctiondefinitionscanbechangedwithoutchangestotheprogramthatusesDayOfYear,Slide10-38,Display10.4(1),Display10.4(2),UsingPrivateVariables,ItisnormaltomakeallmembervariablesprivatePrivatevariablesrequirememberfunctionstoperformallchangingandretrievingofvaluesAccessorfunctionsallowyoutoobtainthevaluesofmembervariablesExample:get_dayinclassDayOfYearMutatorfunctionsallowyoutochangethevaluesofmembervariablesExample:setinclassDayOfYear,Slide10-39,GeneralClassDefinitions,ThesyntaxforaclassdefinitionisclassClass_Namepublic:Member_Specification_1Member_Specification_2Member_Specification_3private:Member_Specification_n+1Member_Specification_n+2;,Slide10-40,DeclaringanObject,Onceaclassisdefined,anobjectoftheclassisdeclaredjustasvariablesofanyothertypeExample:TocreatetwoobjectsoftypeBicycle:classBicycle/classdefinitionlines;Bicyclemy_bike,your_bike;,Slide10-41,TheAssignmentOperator,Objectsandstructurescanbeassignedvalueswiththeassignmentoperator(=)Example:DayOfYeardue_date,tomorrow;tomorrow.set(11,19);due_date=tomorrow;,Slide10-42,ProgramExample:BankAccountClass,ThisbankaccountclassallowsWithdrawalofmoneyatanytimeAlloperationsnormallyexpectedofabankaccount(implementedwithmemberfunctions)StoringanaccountbalanceStoringtheaccountsinterestrate,Slide10-43,Display10.5(1),Display10.5(2),Display10.5(3),Display10.5(4),CallingPublicMembers,Recallthatifcallingamemberfunctionfromthemainfunctionofaprogram,youmustincludethetheobjectname:account1.update();,Slide10-44,CallingPrivateMembers,Whenamemberfunctioncallsaprivatememberfunction,anobjectnameisnotusedfraction(doublepercent);isaprivatememberoftheBankAccountclassfractioniscalledbymemberfunctionupdatevoidBankAccount:update()balance=balance+fraction(interest_rate)*balance;,Slide10-45,Constructors,AconstructorcanbeusedtoinitializemembervariableswhenanobjectisdeclaredAconstructorisamemberfunctionthatisusuallypublicAconstructorisautomaticallycalledwhenanobjectoftheclassisdeclaredAconstructorsnamemustbethenameoftheclassAconstructorcannotreturnavalueNoreturntype,notevenvoid,isusedindeclaringordefiningaconstructor,Slide10-46,ConstructorDeclaration,AconstructorfortheBankAccountclasscouldbedeclaredas:classBankAccountpublic:BankAccount(intdollars,intcents,doublerate);/initializesthebalanceto$dollars.cents/initializestheinterestratetoratepercent/TherestoftheBankAccountdefinition;,Slide10-47,ConstructorDefinition,TheconstructorfortheBankAccountclasscouldbedefinedasBankAccount:BankAccount(intdollars,intcents,doublerate)if(dollars0)|(cents0)|(rate0)cout“Illegalvaluesformoneyorraten”;exit(1);balance=dollars+0.01*cents;interest_rate=rate;Notethattheclassnameandfunctionnamearethesame,Slide10-48,CallingAConstructor(1),Aconstructorisnotcalledlikeanormalmemberfunction:BankAccountaccount1;account1.BankAccount(10,50,2.0);,Slide10-49,CallingAConstructor(2),AconstructoriscalledintheobjectdeclarationBankAccountaccount1(10,50,2.0);CreatesaBankAccountobjectandcallstheconstructortoinitializethemembervariables,Slide10-50,OverloadingConstructors,ConstructorscanbeoverloadedbydefiningconstructorswithdifferentparameterlistsOtherpossibleconstructorsfortheBankAccountclassmightbeBankAccount(doublebalance,doubleinterest_rate);BankAccount(doublebalance);BankAccount(doubleinterest_rate);BankAccount();,Slide10-51,TheDefaultConstructor,AdefaultconstructorusesnoparametersAdefaultconstructorfortheBankAccountclasscouldbedeclaredinthiswayclassBankAccountpublic:BankAccount();/initializesbalanceto$0.00/initializesrateto0.0%/Therestoftheclassdefinition;,Slide10-52,DefaultConstructorDefinition,ThedefaultconstructorfortheBankAccountclasscouldbedefinedasBankAccount:BankAccount()balance=0;rate=0.0;Itisagoodideatoalwaysincludeadefaultconstructorevenifyoudonotwanttoinitializevariables,Slide10-53,CallingtheDefaultConstructor,ThedefaultconstructoriscalledduringdeclarationofanobjectAnargumentlistisnotusedBankAccountaccount1;/usesthedefaultBankAccountconstructorBankAccountaccount1();/Isnotlegal,Slide10-54,Display10.6(1),Display10.6(2),Display10.6(3),InitializationSections,AninitializationsectioninafunctiondefinitionprovidesanalternativewaytoinitializemembervariablesBankAccount:BankAccount():balance(0),interest_rate(0.0);/NocodeneededinthisexampleThevaluesinparenthesisaretheinitialvaluesforthemembervariableslisted,Slide10-55,ParametersandInitialization,MemberfunctionswithparameterscanuseinitializationsectionsBankAccount:BankAccount(intdollars,intcents,doublerate):balance(dollars+0.01*cents),interest_rate(rate)if(dollars0)|(cents0)|(rate0)cout“Illegalvaluesformoneyorraten”;exit(1);Noticethattheparameterscanbeargumentsintheinitialization,Slide10-56,Section10.2Conclusion,CanyouDescribethedifferencebetweenaclassandastructure?Explainwhymembervariablesareusuallyprivate?Describethepurposeofaconstructor?Useaninitializationsectioninafunctiondefinition?,Slide10-57,10.3,AbstractDataTypes,AbstractDataTypes,AdatatypeconsistsofacollectionofvaluestogetherwithasetofbasicoperationsdefinedonthevaluesAdatatypeisanAbstractDataType(ADT)ifprogrammersusingthetypedonothaveaccesstothedetailsofhowthevaluesandoperationsareimplemented,Slide10-59,ClassesToProduceADTs,TodefineaclasssoitisanADTSeparatethespecificationofhowthetypeisusedbyaprogrammerfromthedetailsofhowthetypeisimplementedMakeallmembervariablesprivatemembersBasicoperationsaprogrammerneedsshouldbepublicmemberfunctionsFullyspecifyhowtouseeachpublicfunctionHelperfunctionsshouldbeprivatemembers,Slide10-60,ADTInterface,TheADTinterfacetellshowtousetheADTinaprogramTheinterfaceconsistsofThepublicmemberfunctionsThecommentsthatexplainhowtousethefunctionsTheinterfaceshouldbeallthatisneededtoknowhowtousetheADTinaprogram,Slide10-61,ADTImplementation,TheADTimplementationtellshowtheinterfaceisrealizedinC+TheimplementationconsistsofTheprivatemembersoftheclassThedefinitionsofpublicandprivatememberfunctionsTheimplementationisneededtorunaprogramTheimplementationisnotneededtowritethemainpartofaprogramoranynon-memberfunctions,Slide10-62,ADTBenefits,ChanginganADTimplementationdoesrequirechangingaprogramthatusestheADTADTsmakeiteasiertodivideworkamongdifferentprogrammersOneormorecanwritetheADTOneormorecanwritecodethatusestheADTWritingandusingADTsbreaksthelargerprogrammingtaskintosmallertasks,Slide10-63,ProgramExampleTheBankAccountADT,InthisversionoftheBankAccountADTDataisstoredasthreemembervariablesThedollarspartoftheaccountbalanceThecentspartoftheaccountbalanceTheinterestrateThisversionstorestheinterestrateasafractionThepublicportionoftheclassdefinitionremainsunchangedfromtheversionofDisplay10.6,Slide10-64,Display10.7(1),Display10.7(2),Display10.7(3),InterfacePreservation,TopreservetheinterfaceofanADTsothatprogramsusingitdonotneedtobechangedPublicmemberdeclarationscannotbechangedPublicmemberdefinitionscanbechangedPrivatememberfunctionscanbeadded,deleted,orchanged,Slide10-65,InformationHiding,InformationhidingwasreferedtoearlieraswritingfunctionssotheycanbeusedlikeblackboxesADTsimplementinformationhidingbecauseTheinterfaceisallthatisneededtousetheADTImplementationdetailsoftheADTarenotneededtoknowhowtousetheADTImplementationdetailsofthedatavaluesarenotneededtoknowhowtousetheADT,Slide10-66,Section10.3Conclusion,CanyouDescribeanADT?DescribehowtoimplementanADTinC+?DefinetheinterfaceofanADT?DefinetheimplementationofanADT?,Slide10-67,10.4,IntroductiontoInheritance,Inheritance,InheritancereferstoderivedclassesDerivedclassesareobtainedfromanotherclassbyaddingfeaturesAderivedclassinheritsthememberfunctionsandvariablesfromitsparentclasswithouthavingtore-writethemExampleInChapter6wesawthattheclassofinput-filestreamsisderivedfromtheclassofallinputstreamsbyaddingmemberfunctionssuchasopenandclosecinbelongstotheclassofallinputstreams,butnottheclassofinput-filestreams,Slide10-69,InheritanceExample,NaturalhierarchyofbankaccountsMostgeneral:ABankAccountstoresabalance
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 劳动仲裁合同十篇
- 食品微生物检验技术试题库及答案
- 2025年事业单位工勤技能-湖北-湖北计算机信息处理员一级高级技师历年参考题库含答案解析
- 2025年事业单位工勤技能-湖北-湖北动物检疫员四级(中级工)历年参考题库含答案解析
- 2025年事业单位工勤技能-海南-海南管道工三级(高级工)历年参考题库含答案解析
- 2025年事业单位工勤技能-海南-海南林木种苗工五级(初级工)历年参考题库含答案解析
- 2025年事业单位工勤技能-海南-海南假肢制作装配工五级(初级工)历年参考题库含答案解析
- 2025年事业单位工勤技能-河南-河南图书资料员一级(高级技师)历年参考题库含答案解析
- 2024版挂靠出租车出租合同
- 2025年事业单位工勤技能-江西-江西水利机械运行维护工二级(技师)历年参考题库含答案解析(5套)
- 深圳流动摊贩管理办法
- 《如何治理小金库》课件
- 协及医院老年综合评估表格
- 精选青少版新概念1B-unit1课件
- 高二英语词汇表(含音标、分单元)
- b737培训课件49-6章apu滑油本是针对飞机737CL机型级的概述
- 邮政储汇业务员高级技师理论知识试卷5套(完整版)
- 英语四级词汇大全
- 压力性尿失禁
- SB/T 10029-2012新鲜蔬菜分类与代码
- 居家适老化改造需求评估表
评论
0/150
提交评论