Function pointer - Wikipedia

文章推薦指數: 80 %
投票人數:10人

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, ... Functionpointer FromWikipedia,thefreeencyclopedia Jumptonavigation Jumptosearch Pointerthatpointstoafunction Afunctionpointer,alsocalledasubroutinepointerorprocedurepointer,isapointerthatpointstoafunction.Asopposedtoreferencingadatavalue,afunctionpointerpointstoexecutablecodewithinmemory.Dereferencingthefunctionpointeryieldsthereferencedfunction,whichcanbeinvokedandpassedargumentsjustasinanormalfunctioncall.Suchaninvocationisalsoknownasan"indirect"call,becausethefunctionisbeinginvokedindirectlythroughavariableinsteadofdirectlythroughafixedidentifieroraddress. Functionpointerscanbeusedtosimplifycodebyprovidingasimplewaytoselectafunctiontoexecutebasedonrun-timevalues. Functionpointersaresupportedbythird-generationprogramminglanguages(suchasPL/I,COBOL,Fortran,[1]dBASEdBL,andC)andobject-orientedprogramminglanguages(suchasC++,C#,andD).[2] Contents 1Simplefunctionpointers 1.1ExampleinC 2Functors 3Methodpointers 4InC++ 4.1PointerstomemberfunctionsinC++ 5AlternateCandC++Syntax 5.1CandC++ 5.2C++ 6Seealso 7References 8Externallinks Simplefunctionpointers[edit] Thesimplestimplementationofafunction(orsubroutine)pointerisasavariablecontainingtheaddressofthefunctionwithinexecutablememory.Olderthird-generationlanguagessuchasPL/IandCOBOL,aswellasmoremodernlanguagessuchasPascalandCgenerallyimplementfunctionpointersinthismanner.[3] ExampleinC[edit] Seealso:§ AlternateCandC++Syntax ThefollowingCprogramillustratestheuseoftwofunctionpointers: func1takesonedouble-precision(double)parameterandreturnsanotherdouble,andisassignedtoafunctionwhichconvertscentimetrestoinches. func2takesapointertoaconstantcharacterarrayaswellasanintegerandreturnsapointertoacharacter,andisassignedtoaCstringhandlingfunctionwhichreturnsapointertothefirstoccurrenceofagivencharacterinacharacterarray. #include/*forprintf*/ #include/*forstrchr*/ doublecm_to_inches(doublecm){ returncm/2.54; } //"strchr"ispartoftheCstringhandling(i.e.,noneedfordeclaration) //Seehttps://en.wikipedia.org/wiki/C_string_handling#Functions intmain(void){ double(*func1)(double)=cm_to_inches; char*(*func2)(constchar*,int)=strchr; printf("%f%s",func1(15.0),func2("Wikipedia",'p')); /*prints"5.905512pedia"*/ return0; } Thenextprogramusesafunctionpointertoinvokeoneoftwofunctions(sinorcos)indirectlyfromanotherfunction(compute_sum,computinganapproximationofthefunction'sRiemannintegration).Theprogramoperatesbyhavingfunctionmaincallfunctioncompute_sumtwice,passingitapointertothelibraryfunctionsinthefirsttime,andapointertofunctioncosthesecondtime.Functioncompute_suminturninvokesoneofthetwofunctionsindirectlybydereferencingitsfunctionpointerargumentfuncpmultipletimes,addingtogetherthevaluesthattheinvokedfunctionreturnsandreturningtheresultingsum.Thetwosumsarewrittentothestandardoutputbymain. #include #include //Functiontakingafunctionpointerasanargument doublecompute_sum(double(*funcp)(double),doublelo,doublehi){ doublesum=0.0; //Addvaluesreturnedbythepointed-tofunction'*funcp' inti; for(i=0;i<=100;i++){ //Usethefunctionpointer'funcp'toinvokethefunction doublex=i/100.0*(hi-lo)+lo; doubley=funcp(x); sum+=y; } returnsum/101.0*(hi-lo); } doublesquare(doublex){ returnx*x; } intmain(void){ doublesum; //Usestandardlibraryfunction'sin()'asthepointed-tofunction sum=compute_sum(sin,0.0,1.0); printf("sum(sin):%g\n",sum); //Usestandardlibraryfunction'cos()'asthepointed-tofunction sum=compute_sum(cos,0.0,1.0); printf("sum(cos):%g\n",sum); //Useuser-definedfunction'square()'asthepointed-tofunction sum=compute_sum(square,0.0,1.0); printf("sum(square):%g\n",sum); return0; } Functors[edit] Mainarticle:Functionobject Functors,orfunctionobjects,aresimilartofunctionpointers,andcanbeusedinsimilarways.Afunctorisanobjectofaclasstypethatimplementsthefunction-calloperator,allowingtheobjecttobeusedwithinexpressionsusingthesamesyntaxasafunctioncall.Functorsaremorepowerfulthansimplefunctionpointers,beingabletocontaintheirowndatavalues,andallowingtheprogrammertoemulateclosures.Theyarealsousedascallbackfunctionsifitisnecessarytouseamemberfunctionasacallbackfunction.[4] Many"pure"object-orientedlanguagesdonotsupportfunctionpointers.Somethingsimilarcanbeimplementedinthesekindsoflanguages,though,usingreferencestointerfacesthatdefineasinglemethod(memberfunction).CLIlanguagessuchasC#andVisualBasic.NETimplementtype-safefunctionpointerswithdelegates. Inotherlanguagesthatsupportfirst-classfunctions,functionsareregardedasdata,andcanbepassed,returned,andcreateddynamicallydirectlybyotherfunctions,eliminatingtheneedforfunctionpointers. Extensivelyusingfunctionpointerstocallfunctionsmayproduceaslow-downforthecodeonmodernprocessors,becausebranchpredictormaynotbeabletofigureoutwheretobranchto(itdependsonthevalueofthefunctionpointeratruntime)althoughthiseffectcanbeoverstatedasitisoftenamplycompensatedforbysignificantlyreducednon-indexedtablelookups. Methodpointers[edit] C++includessupportforobject-orientedprogramming,soclassescanhavemethods(usuallyreferredtoasmemberfunctions).Non-staticmemberfunctions(instancemethods)haveanimplicitparameter(thethispointer)whichisthepointertotheobjectitisoperatingon,sothetypeoftheobjectmustbeincludedaspartofthetypeofthefunctionpointer.Themethodisthenusedonanobjectofthatclassbyusingoneofthe"pointer-to-member"operators:.*or->*(foranobjectorapointertoobject,respectively). AlthoughfunctionpointersinCandC++canbeimplementedassimpleaddresses,sothattypicallysizeof(Fx)==sizeof(void*),memberpointersinC++aresometimesimplementedas"fatpointers",typicallytwoorthreetimesthesizeofasimplefunctionpointer,inordertodealwithvirtualmethodsandvirtualinheritance[citationneeded]. InC++[edit] InC++,inadditiontothemethodusedinC,itisalsopossibletousetheC++standardlibraryclasstemplatestd::function,ofwhichtheinstancesarefunctionobjects: #include #include staticdoublederivative(conststd::function&f,doublex0,doubleeps){ doubleeps2=eps/2; doublelo=x0-eps2; doublehi=x0+eps2; return(f(hi)-f(lo))/eps; } staticdoublef(doublex){ returnx*x; } intmain(){ doublex=1; std::cout< usingnamespacestd; classFoo{ public: intadd(inti,intj){ returni+j; } intmult(inti,intj){ returni*j; } staticintnegate(inti){ return-i; } }; intbar1(inti,intj,Foo*pFoo,int(Foo::*pfn)(int,int)){ return(pFoo->*pfn)(i,j); } typedefint(Foo::*Foo_pfn)(int,int); intbar2(inti,intj,Foo*pFoo,Foo_pfnpfn){ return(pFoo->*pfn)(i,j); } typedefint(*PFN)(int); intbar3(inti,PFNpfn){ returnpfn(i); } intmain(){ Foofoo; cout<*m)('A'); //Thisdefines'Ref',afunctionthatacceptsareference-to-'C', //apointer-to-member-of-'C'oftype'Fn',anda'char', //callsthefunctionandreturnstheresult intRef(C&r,FnC::*m,charc){ return(r.*m)(c); }//Ref(r,m,c) //Thisdefines'Ptr',afunctionthatacceptsapointer-to-'C', //apointer-to-member-of-'C'oftype'Fn',anda'char', //callsthefunctionandreturnstheresult intPtr(C*p,FnC::*m,charc){ return(p->*m)(c); }//Ptr(p,m,c) //LEGACY:Notethattomaintainexistingcodebases,theabovedefinitionstylecanstillbeusedfirst; //thentheoriginaltypecanbedefinedintermsofitusingthenewstyle. //Thisdefines'FnC',atypeofpointer-to-member-of-class-'C'oftype'Fn' typedefFnC::*FnC; //'FnC'canbeusedwherever'FnC::*'can FnCfnC=&C::Member; intRefP(C&p,FnCm,charc); Seealso[edit] Delegation(computing) Functionobject Higher-orderfunction Proceduralparameter References[edit] ^AndrewJ.Miller."FortranExamples".http://www.esm.psu.edu/~ajm138/fortranexamples.html.Retrieved2013-09-14.{{citeweb}}:Externallinkin|location=(help)CS1maint:location(link) ^"TheFunctionPointerTutorials".http://www.newty.de/:logo.Retrieved2011-04-13.FunctionPointersarepointers,i.e.variables,whichpointtotheaddressofafunction{{citeweb}}:Externallinkin|location=(help) ^"TheFunctionPointerTutorials".http://www.newty.de/:logo.Retrieved2011-04-13.Importantnote:Afunctionpointeralwayspointstoafunctionwithaspecificsignature!Thusallfunctions,youwanttousewiththesamefunctionpointer,musthavethesameparametersandreturn-type!{{citeweb}}:Externallinkin|location=(help) ^"Expertise:IntermediateLanguage:C++:UseFunctorforCallbacksinC++".http://www.devx.com/:DevX.com.2005-01-31.Retrieved2011-04-13.Ifyouwanttouseamemberfunctionasacallbackfunction,thenthememberfunctionneedstobeassociatedwithanobjectoftheclassbeforeitcanbecalled.Inthiscase,youcanusefunctor[withanexampleonthispage].{{citeweb}}:Externallinkin|location=(help) Externallinks[edit] FAQonFunctionPointers,thingstoavoidwithfunctionpointers,someinformationonusingfunctionobjects FunctionPointerTutorials,aguidetoC/C++functionpointers,callbacks,andfunctionobjects(functors) MemberFunctionPointersandtheFastestPossibleC++Delegates,CodeProjectarticlebyDonClugston PointerTutorials,C++documentationandtutorials CpointersexplainedavisualguideofpointersinC SecureFunctionPointerandCallbacksinWindowsProgramming,CodeProjectarticlebyR.Selvam TheCBook,FunctionPointersinCby"TheCBook" FunctionPointersindBASEdBL,FunctionPointerindBASEdBL Retrievedfrom"https://en.wikipedia.org/w/index.php?title=Function_pointer&oldid=1026099154" Categories:DatatypesSubroutinesHiddencategories:CS1errors:externallinksCS1maint:locationArticleswithshortdescriptionShortdescriptionmatchesWikidataAllarticleswithunsourcedstatementsArticleswithunsourcedstatementsfromAugust2011ArticleswithexampleCcodeArticleswithexampleC++code Navigationmenu Personaltools NotloggedinTalkContributionsCreateaccountLogin Namespaces ArticleTalk English Views ReadEditViewhistory More Search Navigation MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate Contribute HelpLearntoeditCommunityportalRecentchangesUploadfile Tools WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem Print/export DownloadasPDFPrintableversion Languages العربيةDeutschΕλληνικάفارسی한국어ItalianoҚазақша日本語Polskiไทย中文 Editlinks



請為這篇文章評分?