简体   繁体   中英

why my definition of a function that returns the pointer to another function doesn't work?

I am learning pointer to functions, and want to define a function that has the return value which is the pointer to another function. In my sample program fun is trying to return a pointer that points to next . However, the program fails to compile. I have written my thought in the comment, any idea where is the problem?

#include <iostream>

using namespace std;

int next(int );

//define next_fp as a pointer to a function that takes an int and return an int
typedef int (*next_fp)(int);

//define a function that returns a pointer to a function that takes an int and return an int
next_fp fun(next);

int main()
{

    cout << fun(next)(5) <<endl;
    return 0;

}

int next(int n) {
    return n+1;
}

next_fp fun(next)   {
    //fun's return type is next_fp, which is a pointer to
    //a function that take an int and return an int.
    return next;
}

Parameter is not declared properly in function declaration next_fp fun(next); (and definition); next is not a type, it's a name of function.

You should change it to:

next_fp fun(next_fp);

and for definition:

next_fp fun(next_fp next) {
    //fun's return type is next_fp, which is a pointer to
    //a function that take an int and return an int.
    return next;
}
next_fp fun(next);

When declaring a function, you must declare the type of the arguments. Try:

next_fp fun(next_fp next);

// ...

next_fp fun(next_fp next) {
    // ...
}

As stated in the comments, you should avoid using for a parameter a name already used in the same scope for a function. You may add a trailing _ to mark function parameters (my personal convention, feel free to use yours):

next_fp fun(next_fp next_);

This works for me:

#include <iostream>

using namespace std;

int next(int );

//define next_fp as a pointer to a function that takes an int and return an int
typedef int (*next_fp)(int);

//define a function that returns a pointer to a function that takes an int and return an int
next_fp fun(next_fp);

int main()
{
    return 0;
    cout << (fun(next))(5) <<endl;
}

int next(int n) {
    return n+1;
}

next_fp fun(next_fp www)   {
    //fun's return type is next_fp, which is a pointer to
    //a function that take an int and return an int.
    return www;
}

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