C ++ function pointer

Source: Internet
Author: User

1. function pointer Definition

INT (* FP) (int A); // defines a pointer to the function.

Int * FP (int A); // error. This is a function that returns an integer pointer instead of a function pointer.

Int _ tmain (INT argc, _ tchar * argv []) {/////////////////////////////////////// /// // example1cout <functestmethod <<Endl; // output function address int (* fptr) (int I); // defines the function pointer fptr = functestmethod ;//; // assign the address of the function functestmethod to the function pointer fptrcout <fptr (5) <"|" <(* fptr) (15) <Endl; // output FP (5) above, which is written in the Standard C ++. (* FP) (15) This is a standard writing method compatible with C. The two methods agree, but note the difference, avoid writing programs with portability issues! //////////////////////////////////////// /// // Example2cout <functestmethod <endl; // output function address: typedefint (* fptr) (int I); // defines the function pointer type. The type is fptr. Typedef definition can simplify the definition of function pointer fptr F; // use the type name fptr defined by yourself to define a function pointer of F! F = functestmethod; // assign the address of the function functestmethod to the function pointer fptrcout <fptr (5) <"|" <(* fptr) (15) <Endl; // output FP (5) above. This is the standard C ++ writing method. (* FP) (15) This is a standard writing method compatible with C language, however, be sure to differentiate to avoid portability issues for written programs! Return 0;} int functestmethod (int I) {return I ;}

  

2. The function pointed to by the function pointer must be a global function or a static function of the class.

class FuncPtr{typedef int (*func)(void);public:void FuncPtrTet(func func1){(*func1)();};static int display(void){cout <<"display"<<endl;return 0;}};

  

int display2(void){cout <<"display2"<<endl;return 2;}

Implementation

int _tmain(int argc, _TCHAR* argv[]){FuncPtr f;f.FuncPtrTet(FuncPtr::display);f.FuncPtrTet(display2);return 0;}

  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.