"C + + Primer, 5e" function pointer

Source: Internet
Author: User

A simple example:

#include <iostream>using namespacestd;intSumintXinty) {    returnX +y;}intMain () {cout<< sum (1,2) <<Endl; int(*PF) (int,int);//not initializedPF =sum; cout<< PF (3,4) <<Endl; /*Output:3 7*/    return 0;}

In case of overloading, the compiler precisely matches the function by pointer type.

#include <iostream>using namespacestd;intSumintXinty) {    returnX +y;}intSumintXDoubley) {cout<<"sum2"<<Endl; returnX +y;}intMain () {cout<< sum (1,2) <<Endl; int(*PF) (int,int);//not initializedPF =sum; cout<< PF (3,4) <<Endl; /*Output:3 7*/    return 0;}

To use a function as an argument:

#include <iostream>using namespacestd;intSumintXinty) {    returnX +y;} typedef decltype (SUM) func;intUseInt2 (intXintY, func f) {    returnf (x, y);}intMain () {cout<< UseInt2 (3,4, sum) <<Endl; /*output = 7*/    return 0;}

The return type is not automatically converted to a pointer, we must display the return type as a pointer, but I think the return function is useless unless it is inside the function that can also be used to construct functions such as Python.

Practice

6.54

 #include <iostream> #include  <vector> using  namespace   STD;  int  sum (int  x, int   y) { return  x + y;}  int   main () { using  pf = int  (*) (int , int   <pf> Pfvec;  return  0  ;}  

6.55 & 6.56

#include <iostream>#include<vector>using namespacestd;intAddintXinty) {    returnX +y;}intSubtractintXinty) {    returnX-y;}intMultiplyintXinty) {    returnX *y;}intDivideintXinty) {    returnX/y;}intMain () {usingPF =int(*) (int,int); Vector<pf>Pfvec;    Pfvec.push_back (add);    Pfvec.push_back (subtract);    Pfvec.push_back (multiply);    Pfvec.push_back (divide);  for(pf F:pfvec) {cout<< F ( A,4) <<Endl; }    return 0;}

Output Result:

 - 8  - 3

"C + + Primer, 5e" function pointer

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.