简体   繁体   中英

Passing pointer to function as parameter

I have the following code:

#include<iostream>
using namespace std;

typedef void (*HandlerFunc)(int, int);
HandlerFunc  mr;
HandlerFunc mm()
{
    return mr;
}

void sample(int a, int b, HandlerFunc func)
{
}

void main()
{
     sample(1, 2, mm);
}

Here I'm trying to pass a function of type HandlerFunc to another function, but I am getting an error:

Error :*: cannot convert parameter 3 from 'void (__cdecl *(void))(int,int)' to 'void (__cdecl *)(int,int)'

If I type cast as sample(1, 2, (HandlerFunc)mm); everything works fine.
Can anyone tell what is the way to solve the error issue?

HandlerFunc mm()
{...}

should be:

void mm(int, int)
{...}

Your function sample() takes a pointer to function( you typedef d as HandlerFunc ) as last argument. The address of the function you pass as this argument must match the type of the function to which it is a pointer.

No, no, you've confused the types. mm is a function that returns a function pointer of the appropriate type. However, mm itself is not of the appropriate type - it doesn't accept any parameters.

You should pass mr in main, or pass mm() (that is - call mm and pass the return value)

The code in main should be:

sample(1,2,mm());

as mm returns a HandlerFunc, it isn't one itself.

HandlerFunc mm() 
{     
   return mr; 
}  

This means nm is function which will not receive any agruments( void ), and it will reutrn a pointer to function of type void (*)(int, int)

so that only you are getting that error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM