为什么我定义一个返回指向另一个函数的函数的函数不起作用?

时间:2016-11-02 08:48:13

标签: c++ pointers

我正在学习函数的指针,并希望定义一个具有返回值的函数,该函数是指向另一个函数的指针。在我的示例程序中,fun尝试返回指向next的指针。但是,该程序无法编译。我在评论中写下了自己的想法,知道问题在哪里?

#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;
}

3 个答案:

答案 0 :(得分:1)

在函数声明next_fp fun(next);(和定义)中未正确声明参数; next不是类型,它是函数的名称。

您应将其更改为:

next_fp fun(next_fp);

和定义:

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;
}

答案 1 :(得分:1)

next_fp fun(next);

声明函数时,必须声明参数的类型。尝试:

next_fp fun(next_fp next);

// ...

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

如评论中所述,您应该避免为参数使用已在函数的同一范围中使用的名称。您可以添加一个尾随_来标记函数参数(我的个人约定,随意使用您的):

next_fp fun(next_fp next_);

答案 2 :(得分:0)

这对我有用:

#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;
}