雙語版C++程序設計(第3版) 課件 7 Functions_第1頁
雙語版C++程序設計(第3版) 課件 7 Functions_第2頁
雙語版C++程序設計(第3版) 課件 7 Functions_第3頁
雙語版C++程序設計(第3版) 課件 7 Functions_第4頁
雙語版C++程序設計(第3版) 課件 7 Functions_第5頁
已閱讀5頁,還剩56頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Chapter7Functions

7.1IntroductionAfunctionisablockofstatementscalledbynametocarryoutaspecifictaskInordertoreducethecomplexityofprograms,theyhavetobebrokenintosmaller,lesscomplexparts.FunctionsandclassesarethebuildingblocksofaC++program.functionsinthestandardlibrary:built-in,pre-writteninC++Line11callsthefunctionsqrt()tocalculatethesquarerootofthevalueinthevariablen7.1IntroductionC++allowsaprogrammertowritefunctionstoaddtothosealreadyathandinthestandardlibrary.Likevariables,functionsmustbedeclaredbeforetheyareused.Line7declaresstarstobeafunctionThefirstvoidonline7declaresthetypeofthefunctionstars()Thesecondvoidinformsthecompilerthat‘stars’willnotreceiveanydatafromthecallingprogram.Thesecondvoidisoptional.-----prototypeofthefunctionstars()----7.1IntroductionProgramExampleP7BLines22to26definethefunctionLine22:functionheaderLine24-25:functionbody7.2Functionarguments(函數實參)Functionstar()candisplay11asterisks,thenhowtodisplayavariablenumberofasterisks?Newfunctionstars():takeavaluepassedtoitanddisplaythenumberofasterisksspecifiedinthatvalue.7.2FunctionargumentsProgramExampleP7CRemarkThisnumberiscalledanargumentReceivedbytheparameternumdeclaredasanintegerinline23RemarkTheparametersofafunctionareknownonlywithinthefunction.Line25ofthefunctionstars()nowusesthevariablenumtodecidehowmanytimes*isdisplayed.7.2FunctionargumentsAnewprogramspecifies:thenumbercharactertodisplaydisp_chars()usestwoparameters:num(thenumberoftimestodisplayacharacter)ch(thecharactertodisplay)7.2FunctionargumentsThevariablenamesusedintheprototypeareoftenthesameasthoseusedfortheparametersinthefunctionheader.Itisgoodpracticetoplacecommentsafterthefunctionprototypetodescribethefunctionanditsparameters.Theprototypeandtheaccompanyingcommentsareknownasthefunctioninterface.7.3Defaultparametervalues(默認的形參值)Afunctionparameterthatisnotpassedavaluecanbeassignedadefaultvalue.Thesecondargumentisomitted.Thesetwoareequivalent.Ifaparameterisprovidedwithadefaultvalue,alltheparameterstoitsrightmustalsohaveadefaultvalue.√×7.4ReturningavaluefromafunctionProgramExampleP7ETodefineandcallafunctionwithreturnvalue,youshouldnotice:functionprototypefunctionheader7.4ReturningavaluefromafunctionThegeneralformatofthereturnstatement:Examples:Thesetwoblocksareequivalent:7.4ReturningavaluefromafunctionAfunctioncallcanbeusedanywhereinaprogramwhereavariablecanbeused7.5Inlinefunctions(內聯函數)Inlinefunctionscanreducethefunctionprocessingoverheads.Tomakeafunctioninline,precedethefunctionprototypewiththekeywordinline.Whenaninlinefunctionisusedinaprogram,thecompilerreplaceseverycalltothefunctionwiththeprogramstatementsinthefunctionIngeneral,considerinliningafunctionwhenthefunctioncontains1~3linesofcode.7.6PassingargumentsbyvaluePassingbyvalueAcopyoftheargumentvaluesispassedtothefunctionparametersThevalueoftheargumentcannotbechangedwithinthefunctionAcopyofthevalueofaispassedtopChangingthevalueofphasnoeffectona7.6PassingargumentsbyvalueThevalueoftheparametercanbepreventedfromchangewithinafunctionbymakingitaconstant.Todothis,placethekeywordconstbeforetheparameterinthefunctionprototypeandfunctionheader.7.7Passingargumentsbyreference(引用)Areferenceisasynonymoranaliasforanexistingvariable.Areferencetoavariableisdefinedbyadding&afterthevariable’sdatatype.Areferencemustalwaysbeinitializedwhenitisdefined

risareferenceton

nandrbothrefertothesamevalue

risnotacopyofn,butismerelyanothernamefornAchangetonwillalsoresultinachangetor7.7PassingargumentsbyreferenceProgramExampleP7GaandprefertothesamestoragelocationChangingthevalueofpalsochangesthevalueofa7.7PassingargumentsbyreferenceProgramExampleP7HArgumentspassedbyreferencelocalvariableThevariabletempisalocalvariabletothefunctionswap_vals().Localvariablesareknownonlywithinthefunctionwheretheyaredefined.7.8Passingaone-dimensionalarraytoafunctionArrayscanonlybepassedbyreferencetoafunction.Toavoidtheoverheadofcopyingalltheelementsofanarray,thatpassingbyvaluewouldentailProgramExampleP7I:containsafunctionsum_array()thatsumstheelementsofanintegerarraypassedtoitfrommain().7.8Passingaone-dimensionalarraytoafunctionLine16callssum_array()tocalculatethesumofthevaluesinthearrayvalues.Theargumentsarethenameandthenumberofelementsinthearray.[and]arenecessarytoindicatethattheparameterisareferencetoanarray.Thenumberofelementsisnotrequiredinthebracketsforaone-dimensionalarraytohandledifferentsizearray.Constinformsthecompilerthatwithinthefunctionsum_array(),arrayisread-onlyandcannotbemodified.Inline20arrayisareferencetovalues.Becausearrayscanonlybepassedbyreference,&isnotrequired.ProgramExampleP7J7.8Passingaone-dimensionalarraytoafunctionInsteadofcommentslistingtheparametersandreturnvalue,preandpostconditioncommentsareused.Inthepreconditioncomment,theconditionsthatmustexistbeforeafunctionmaybesuccessfullycalledarelisted.Inthepostconditioncomment,theconditionsthatwillexistafterthefunctioniscalledarelisted.ProgramExampleP7J…continued7.8Passingaone-dimensionalarraytoafunction7.8Passingaone-dimensionalarraytoafunction7.8Passingaone-dimensionalarraytoafunction7.9Passingamulti-dimensionalarraytoafunctionWhenamulti-dimensionalarrayispassedtoafunction,thefunctionparameterlistmustcontainthesizeofeachdimensionofthearray,exceptthefirst.7.9Passingamulti-dimensionalarraytoafunction7.9Passingamulti-dimensionalarraytoafunctionTheelementsofatwo-dimensionalarrayarestoredrowbyrowincontiguousmemorylocations.Anyelementarray[i][j]inprogramP7Khasanoffseti*2+jfromthestartingmemorylocationofarray[0][0].Inordertocalculatetheoffset,thenumberofcolumns(=2)isrequired;hencetheneedforthecompilertoknowthevalueoftheseconddimension7.10PassingastructurevariabletoafunctionPassingastructurevariabletoafunctionpassacopyofthemembervaluestothatfunction,thismeansthatthevaluesinthestructurevariablecannotbechangedwithinthefunction.Thevaluesinastructurevariablecanonlybechangedfromwithinafunctionifthevariableispassedbyreferencetothefunction.ProgramExampleP7L:demonstratespassingastructurevariablebyvalueandpassingastructurevariablebyreferencetotwodifferentfunctions.7.10PassingastructurevariabletoafunctionProgramExampleP7LWhenastructuretemplateisdefinedoutsidemain(),itmakesthestructuretemplateglobal.Thismeansthatthestructuretemplateisknowninmain()andindisplay_student_data()andget_student_data().7.10PassingastructurevariabletoafunctionProgramExampleP7L…continuedWhenastructurevariableispassedbyvaluetoafunction,theentirestructuredatamustbecopiedtothefunctionparameter.Foralargestructure,thisisasignificantoverheadanditispreferabletouseareference.Iftheargumentisn‘tchangedbythefunction,theconstkeywordshouldbeused.7.10PassingastructurevariabletoafunctionProgramExampleP7L…continued7.11PassingastringtofunctionThesameconsiderationsshouldbekeptinmindwhenusingstringsasargumentsaswhenusingstructurevariablesasarguments,i.e.passingastringbyvaluemeanscopyingallthecharactersofthestringtoafunctionparameter.Toavoidthisoverheaditispreferabletopassstringsbyreference.7.11.1PassingaC++stringtoafunctionProgramExampleP7MdemonstratespassingaC++stringbyconstreferencetoafunctionthatcountsthenumberofvowelsinthestring.7.11Passingastringtofunction7.11Passingastringtofunction7.11.2PassingaC-stringtoafunctionTouseC-stringsinsteadofC++stringsinprogramP7M,thefollowingmodificationsmustbemadetotheprogram:7.12Recursion(遞歸)Recursionisaprogrammingtechniqueinwhichaproblemcanbedefinedintermsofitself.Thetechniqueinvolvessolvingaproblembyreducingtheproblemtosmallerversionsofitself.Thefactorialofapositiveintegeristheproductoftheintegersfrom1throughtothatnumber.(a)0!=1.Thisiscalledthebasecase.(b)Forapositiveintegern,factorialnisntimesthefactorialofn-1.Thisiscalledthegeneralcaseclearlyindicatesthatfactorialisdefinedintermsofitself.7.12RecursionUsingthedefinition,factorial3iscalculatedasfollows:Thevalueofnis3so,using(b)above,3!=3*2!Nextfind2!Heren=2so,using(b)again,2!=2*1!Nextfind1!Heren=1so,using(b)again,1!=1*0!Nextfind0!Inthiscaseusing(a),0!isdefinedas1.Substitutingfor0!gives1!=1*1=1.Substitutingfor1!gives2!=2*1!=2*1=2.Finally,substitutingfor2!gives3!=3*2!=3*2=6.7.12RecursionProgramExampleP7N7.12RecursionProgramExampleP7NNotethat●Everyrecursivefunctionmusthaveatleastonebasecasewhichstopstherecursion●Thegeneralcaseeventuallyreducestoabasecase.7.12RecursionThefactorialfunctioncouldbewrittenusingiterationTherecursiveversionwillexecutemoreslowlythantheiterativeequivalentbecauseoftheaddedoverheadofthefunctioncalls.Theadvantageoftherecursiveversionisthatitisclearerbecauseitfollowstheactualmathematicaldefinitionoffactorial.7.13Functionoverloading(函數重載)Functionoverloadingisusedwhenthereisaneedfortwoormorefunctionstoperformsimilartasks,butwhereeachfunctionrequiresadifferentnumberofargumentsand/ordifferentargumentdatatypes.Usingdifferentfunctionswiththesamenameinaprogramiscalledfunctionoverloadingandthefunctionsarecalled

overloadedfunctions.Functionoverloadingrequiresthateachoverloadedfunctionhaveadifferentparameterlist,i.e.adifferentnumberofparametersoratleastoneparameterwithadifferentdatatype.7.13FunctionoverloadingProgramExampleP7OThecompilerdecideswhichofthetwosum_array()functionstocallbasedonmatchingargumentswithparameters.7.13FunctionoverloadingProgramExampleP7O…continued7.14Storageclassesautoandstatic

(auto和static存儲類型)7.14.1autoThevariablesdefinedinsideafunctionareauto(automatic)bydefault.Everytimeafunction(includingmain())isentered,storageforeachautovariableisallocated.Whenthefunctioniscompleted,theallocatedstorageisfreed,andanyvaluesintheautovariablesarelost.Suchvariablesareknownaslocalvariablesandareknownonly

withinthefunctioninwhichtheyaredefined.Thevariablesvar1andvar2havebeendefinedwiththestorageclassauto.Thekeywordautomaybeomitted.7.14Storageclassesautoandstatic7.14.2staticstaticvariables,likeautovariables,arelocaltothefunctioninwhichtheyaredefined.staticvariablesareallocatedstorageonlyonceandsoretaintheirvaluesevenafterthefunctionterminates.ProgramExampleP7P7.14StorageclassesautoandstaticProgramExampleP7P…continuedVariablestatic_varwasinitializedonlyonceandretaineditsvaluebetweeneachfunctioncall,i.e.thevalueofstatic_varwasincrementedeverytimeany_func()wascalled.Theautovariableauto_varwascreatedandinitialisedto0everytimethefunctionwasenteredandthenincrementedto1.7.15Thescopeofavariable(變量的作用域)Thescopeofavariablereferstothepartoftheprograminwhichavariablecanbeaccessed.blockscopeglobalscope7.15.1BlockscopeAblockisoneormorestatementsenclosedinbraces{and}thatalsoincludesvariabledeclarations.Avariabledeclaredinablockisaccessibleonlywithinthatblock.7.15ThescopeofavariableBlockscope7.15Thescopeofavariable…continued7.15ThescopeofavariableVariablesdeclaredinsidetheparenthesesofaforareaccessiblewithintheparentheses,aswellasinthestatement(s)containedintheforloop.7.15Thescopeofavariable7.15.2GlobalscopeAvariabledeclaredoutsidemain()isaccessiblefromanywherewithintheprogramandisknownasaglobalvariable.Becauseglobalvariablesareknown,andthereforecanbemodified,withineveryfunction,theycanmakeaprogramdifficulttodebugandmaintain.Globalvariablesarenotasubstituteforfunctionarguments.Apartfromitsownlocalvariables,afunctionshouldhaveaccessonlytothedataspecifiedinthefunctionparameterlist.7.15Thescopeofavariable7.15.3ReusingavariablenameItispermissibletogiveavariablethesamenameasanothervariableinanotherblock.Thisisknownasnamereuse(名重用).ProgramP7QIfavariableisdeclaredinaninnerblockandifavariablewiththesamenameisdeclaredinasurroundingblock,thevariableintheinnerblockhidesthevariableofthesurroundingblock.Ifaglobalvariableishiddenbyalocalvariable,theglobalvariablecanstillbeaccessedusingtheunaryscoperesolutionoperator::7.15ThescopeofavariableProgramP7Q…continued7.15ThescopeofavariableProgramP7Q…continued7.16Mathematicalfunctions(數學函數)Touseanyofthemathematicalfunctionsplacethestatement#include<cmath>atthestartoftheprogram.7.16.1SometrigonometricfunctionsProgramExampleP7R:demonstratessin(),cos()andtan()functions.7.16MathematicalfunctionsProgramExampleP7R7.16Mathematicalfunctions7.16.2Pseudo-randomnumberfunctions(偽隨機數函數)

Tousethepseudo-randomgeneratingfu

溫馨提示

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

評論

0/150

提交評論