c++ - "error: ’ myfn' declared as function returning a function"是什么意思?

标签 c++ c function-pointers

我正在尝试编写一个返回函数指针的函数。这是我的最小示例:

void (*myfn)(int)()  // Doesn't work: supposed to be a function called myfn
{                    // that returns a pointer to a function returning void
}                    // and taking an int argument.

当我用 g++ myfn.cpp 编译它时,它打印出这个错误:

myfn.cpp:1:19: error: ‘myfn’ declared as function returning a function
myfn.cpp:1:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

这是否意味着我不能返回函数指针?

最佳答案

你可以返回一个函数指针,正确的语法是这样的:

void (*myfn())(int)
{
}

完整示例:

#include <cstdio>

void retfn(int) {
    printf( "retfn\n" );
}

void (*callfn())(int) {
    printf( "callfn\n" );
    return retfn;
}

int main() {
    callfn()(1); // Get back retfn and call it immediately
}

编译和运行是这样的:

$ g++ myfn.cpp && ./a.out
callfn
retfn

如果有人能很好地解释为什么 g++ 的错误消息表明这是不可能的,我很想听听。

关于c++ - "error: ’ myfn' declared as function returning a function"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18773359/

相关文章:

c++ - 在可移动类型的构造函数 lambda 中安全使用 captured this

c++ - 文件流析构函数可以在 C++ 中抛出异常吗?

c - 为什么数组的地址等于它在 C 中的值?

c - 将双指针传递给函数作为引用 - c

c# - 将 C 函数指针设置为 C# 函数

c++ - std::decay 和按值传递之间有什么区别?

c++ - 在模板类中使用两个类型转换运算符时出现问题

c - 在 c 中有一个结构的 void* 成员是什么意思?

c - 如何从C中的函数中获取函数名和参数个数?

c - C 中的函数指针如何工作? - 具体例子