




已阅读5页,还剩68页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1 Chapter8Scope Lifetime andMoreonFunctions 2 Chapter8Topics LocalScopeandGlobalScopeofanIdentifierDeterminewhichVariableinaprogramarelocalDeterminingtheLifetimeofaVariableWritingaValue ReturningFunctionforaTask 3 8 1ScopeofIdentifier Scope theregionofprogramcodewhereitislegaltousethatidentifier ClassscopeLocalscope blockscope Globalscope filescope 4 8 1ScopeofIdentifier Scope theregionofprogramcodewhereitislegaltousethatidentifier includevoidmain intx 256 cout x x endl AlocalvariabledeclaredinablockhasaLocalscope 5 if alpha 3 intn cin n beta beta n Thescopeoflocalvariablen Exampleofalocalvariabledeclaredinablock 6 8 1 1LocalScopeandGlobalScope foranidentifierthatisdeclaredinsideablock thisincludesfunctionparameters foranidentifierthatisdeclaredoutsideofallnamespaces functionsandclasses extendsfromthepointofdeclarationtotheendoftheblock extendsfrompointofdeclarationtotheendoftheentirefile LocalScope GlobalScope 7 constfloatTAX RATE 0 05 globalconstantfloattipRate globalvariablevoidhandle int float functionprototypeintmain intage ageandbilllocaltothisblockfloatbill handle age bill return0 voidhandle inta floatb floattax a b andtaxlocaltothisblock 8 8 1 2NamePrecedence orNameHiding whenafunctiondeclaresalocalidentifierwiththesamenameasaglobalidentifier thelocalidentifiertakesprecedencewithinthatfunction 9 includeusingnamespacestd voidsomefunc float constinta 17 intb c intmain b 8 c 6 somefunc 42 8 return0 voidsomefunc floatc floatb b c cout b 10 NamePrecedence Whenanexpressionreferstoanidentifier 1 firstchecksthelocaldeclarations2 ifitisn tlocal compilerworksoutwardthrougheachlevelofnestinguntilitfindsanidentifierwithsamename 3 ifcompilerreachesglobaldeclarationsandstillcan tfindtheidentifier anerrormessageresults 11 NamePrecedenceImplementedbyCompiler includeusingnamespacestd voidSomeFunc float constinta 17 intb c intmain b 8 c 6 SomeFunc 42 8 return0 voidSomeFunc floatc floatb b c 12 inthefunctionbodyaccessestheglobevariable includeintx voidmain intx 256 cout globalvariablex x endl cout localvariablex x endl 13 globevariable inthefunctionbodyaccessestheglobevariable includeintx voidmain intx 256 cout globalvariablex x endl cout localvariablex x endl 14 localvariable inthefunctionbodyaccessestheglobevariable includeintx voidmain intx 256 cout globalvariablex x endl cout localvariablex x endl 15 inthefunctionbodyaccessestheglobevariable includeintx voidmain intx 256 cout globalvariablex x endl cout localvariablex x endl 16 8 1 2ScopeRules Functionnamehasglobalscope Functionparameterscopeisidenticaltoscopeofalocalvariabledeclaredintheoutermostblockofthefunctionbody Globalvariable orconstant scopeextendsfromdeclarationtotheendofthefile exceptasnotedinrule5 17 Localvariable orconstant scopeextendsfromdeclarationtotheendoftheblockwheredeclared Thisscopeincludesanynestedblocks exceptasnotedinrule5 5 Anidentifier sscopedoesnotincludeanynestedblockthatcontainsalocallydeclaredidentifierwiththesamename localidentifiershavenameprecedence 8 1 2ScopeRules 18 includeinti voidprint voidmain for i 0 i 5 i print voidprint for i 0 i 5 i cout cout n 19 includeinti voidprint voidmain for i 0 i 5 i print voidprint for i 0 i 5 i cout cout n Output 20 8 1 3Variabledeclarationanddefinition intSquare intn intresult result n n returnresult intSquare intn Memoryallocated内存分配 Nomemoryreserved无内存保留 intsomeInt externintsomeInt 21 Externaldeclaration Itstatesaglobalvariablelocatedinanotherfile 它声明了一个在其它文件中定义的变量 Nomemoryisreservedforanexternaldeclaration 对外部变量不分配存储空间 Thepurposeofanexternaldeclarationisthatthecompilercandotypechecking 声明外部变量的目的是让编译软件作类型检查 22 8 1 4Namespace AmechanismthattheprogrammercancreateanamedscopeThescopeofanidentifierdeclaredinanamespaceextendsfromthepointofdeclarationtotheendofthenamespacebodyAnditsscopeincludesthescopeofausingdirectivespecifyingthatnamespace 23 8 1 4Namespace namespacestd intabs int Anamespacedefinition namespaceidentifier namespace body 24 3WaystoUseNamespaceIdentifiers useaqualifiednameitconsistingofthenamespace thescoperesolutionoperator andthedesiredtheidentifieralpha std abs beta writeausingdeclarationusingstd abs alpha abs beta writeausingdirectivelocallyorgloballyusingnamespacestd alpha abs beta 25 Scopecategories作用域类型 Classscope localscope globalscope Namespacescope 26 8 2LifetimeofVariables变量的生存期 Theperiodoftimeduringprogramexecutionwhenanidentifierhasmemoryallocatedtoit 变量的生存期是指在程序运行过程中 变量实际占用内存或寄存器的时间 27 8 2 1LifetimeofLocalVariablesinFunctions theirstorageiscreated allocated whencontrolentersthefunction 当执行函数的时候 为函数中声明的局部变量分配存储空间 localvariablesare alive whilefunctionisexecutingtheirstorageisdestroyed deallocated whenfunctionexits 28 8 2 2LifetimeofGlobalVariables theirlifetimeisthelifetimeoftheentireprogramtheirmemoryisallocatedwhenprogrambeginsexecutiontheirmemoryisdestroyedwhentheentireprogramterminates 29 8 2 3AutomaticVariableandStaticVariable storageforautomaticvariableisallocatedatblockentryanddestroyedatblockexit storageforstaticvariableremainsallocatedthroughoutexecutionoftheentireprogram AutomaticVariable StaticVariable 30 Bydefault localvariablesareautomatictoobtainastaticlocalvariable youmustusethereservedwordstaticinitsdeclaration 31 8 2 4Initializationindeclaration声明时初始化 Forautomaticvariables initializationoccurseachtimecontrolenterstheblockForstaticvariables initializationonlyoccursonce intsum sum 0 intsum 0 32 StaticandAutomaticLocalVariables intpopularSquare intn staticinttimesCalled 0 initializedonlyonceintresult n n initializedeachtimetimesCalled timesCalled 1 cout Call timesCalled endl returnresult 33 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 35 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 36 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 37 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 38 1 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 39 2 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 40 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 41 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 42 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 43 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 44 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 45 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 46 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 47 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 48 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 49 1 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 50 autoa 1staticb 23autoa 1staticb 34 3 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 51 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 52 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 53 例4 12静态变量与自动变量的测试 includeintfunc voidmain cout func endl cout func endl intfunc inta 0 自动变量staticintb 1 静态变量a b cout autoa a endl cout staticb b endl returna b autoa 1staticb 23autoa 1staticb 34 54 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 55 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 56 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 57 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 58 autoa 1staticb 23autoa 1staticb 34 exampleStaticandAutomaticLocalVariables includeintfunc voidmain cout func endl cout func endl intfunc inta 0 staticintb 1 a b cout autoa a endl cout staticb b endl returna b 59 8 3Interfacedesign DonotletfunctionscommunicatebydirectlychangeglobalvariablesSideeffect anyeffectofonefunctiononanotherthatisnotapartoftheexplicitlydefinedinterfacebetweenthemTheonlyexternaleffectthatafunctionshouldhaveistotransferinformationthroughthewell structuredinterfaceoftheparameterlist 60 8 3 1SideEffect NonlocalvariablesareaccessedonlythroughtheparameterlistIncoming onlyparametersaredefinedasvalueparameters 61 8 3 2GlobalConstants Therearetwoadvantages Easeofchange 易于修改 Consistency 能保持数据的一致性 62 8 4Value returningFunctions includeintSquare int prototypesintCube int usingnamespacestd intmain cout Thesquareof27is Square 27 endl functioncallcout Thecubeof27is Cube 27 endl functioncallreturn0 63 RestofProgram intSquare intn returnn n intCube intn returnn n n 64 Featuresofvalue returningfunction HeadingbeginswiththedatatypeThereturnstatementhasareturnvalue Functionvaluetype thedatatypeoftheresultvaluereturnedbyafunction 65 SyntaxTemplateforFunctionDefinition DataTypeFunctionName ParameterList Statement Ifdatatypeisomitted intisthedefaulttype 66 8 4 1ABooleanFunction boolIsTriangle in floatangle1 in floatangle2 in floatangle3 Functionchecksif3incomingvaluesaddupto180degrees formingavalidtriangle PRECONDITION angle1 angle2 angle3areassigned POSTCONDITION FCTNVAL true ifsumiswithin0 000001of 180 0degrees false otherwise return fabs angle1 angle2 angle3 180 0 0 000001 67 SomePrototypesinHeaderFile intisalpha charc
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 国家能源黄山市休宁县2025秋招心理测评常考题型与答题技巧
- 2025年4月四川成都市金牛区中医医院招聘17人模拟试卷(含答案详解)
- 中国联通昆明市2025秋招技能类专业追问清单及参考回答
- 中国广电阜新市2025秋招写作案例分析万能模板直接套用
- 办公室租赁合同合集15篇
- 单位股东合作协议书
- 2025年芜湖繁昌区教育高层次人才招引25人模拟试卷有答案详解
- 2025年黑河市北安市公开招聘社区工作者17人考前自测高频考点模拟试题完整答案详解
- 土地征收补偿合同范本5篇
- 2025年消费金融行业用户画像与精准营销策略在智能家居领域的应用报告
- 云南师大附中2024年数学高一下期末联考试题含解析
- 供应链管理综合实验实验报告
- (正式版)JBT 5300-2024 工业用阀门材料 选用指南
- 2024量子人工智能技术白皮书-量子信息网络产业联盟-2024.1
- 公务员考试培训-判断推理通关秘籍
- 第13课《警惕可怕的狂犬病》 课件
- 《社会工作伦理案例分析》课件 儿童和青少年社会工作伦理
- HSK标准教程5下-课件-L2
- 艺人明星形象代言肖像权使用合同模板
- 毕业设计论文-计算机类
- 工作单位接收函
评论
0/150
提交评论