C + + function pointers

Source: Internet
Author: User

1#include <iostream>2 using namespacestd;3 4 intPrintval (inti) {5cout<<i<<Endl;6     return 0;7 }8 9 intADD (intIintj) {Ten     returni+J; One } A  - voidCompare (intIintj) { -     if(i==j) thecout<<i<<"=="<<j<<Endl; -     Else if(i>j) -cout<<i<<">"<<j<<Endl; -     Else +cout<<i<<"<"<<j<<Endl; - } +typedefint(*pfunc) (int); A  at intMain () { -PFunc P1 =Printval; -     int(*P2) (int,int); -P1 (7); -P1 = &Printval; -(*P1) (8); inP2 =Add; -COUT&LT;&LT;P2 (4,5) <<Endl; to  +P2 = reinterpret_cast<int(*) (int,int) > (Compare);//make a strong turn -  theP2 (4,5); *}

1, the Writing method type (*name) (param);

2, function pointer writing is more complex, generally use typedef to simplify.

3. The function prototype must be consistent with the prototype when the function pointer is defined, or it will cause a compilation error. However, in some special cases, you can use the reinterpret_cast operation to convert between function pointers of different types.

4, there is a function called "callback function". The callback function is a kind of dynamic application pattern which defines the function's prototype, and the function body is handed to the third party to implement. When implementing a function call, first pass the address of the callback function as one of the parameters to the key function. The callback function is invoked inside the keynote function through a function pointer. The mechanism of the callback function breaks the limit of static binding between the keynote function and the dropped function, and provides a convenient means for the user to make full use of the operating system.

C + + function pointers

Related Article

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.