C++ 如何将C函数指针迁移到C++;?

C++ 如何将C函数指针迁移到C++;?,c++,c,pointers,function-pointers,C++,C,Pointers,Function Pointers,以下是在C中使用函数指针: #include <stdio.h> void bar1(int i){printf("bar1 %d\n", i+1);} void bar2(int i){printf("bar2 %d\n", i+2);} void foo(void (*func)(), int i) {func(i);}; int main() { foo(bar2, 0); } 试图编译它时,会出现以下错误: $ g++ main.cpp main.cpp:7:39:

以下是在C中使用函数指针:

#include <stdio.h>
void bar1(int i){printf("bar1 %d\n", i+1);}
void bar2(int i){printf("bar2 %d\n", i+2);}
void foo(void (*func)(), int i) {func(i);};
int main() {
    foo(bar2, 0);
}
试图编译它时,会出现以下错误:

$ g++ main.cpp
main.cpp:7:39: error: too many arguments to function call, expected 0, have 1
void foo(void (*func)(), int i) {func(i);};
                                 ~~~~ ^
main.cpp:10:2: error: no matching function for call to 'foo'
        foo(bar2, 0);
        ^~~
main.cpp:7:6: note: candidate function not viable: no known conversion from 'void (int)' to 'void (*)()' for 1st argument
void foo(void (*func)(), int i) {func(i);};
     ^
2 errors generated.
<如何迁移C函数指针到C++中?< /p> < p> >,<代码>无效> f>)/>代码>声明<代码> f>代码>为函数,该函数接受未指定的参数数目,并返回<代码> int <代码>。在C++中,它声明<代码> f>代码>是一个不带参数的函数,返回<代码> int <代码>。在C语言中,如果要编写一个不带参数的函数,可以使用
void
作为参数列表:
void f(void)
声明一个不带参数且不返回任何内容的函数


除非您有充分的理由不这样做,否则编写问题中代码的方法是
voidfoo(void(*func)(int),inti)
。也就是说,
func
是指向一个函数的指针,该函数接受一个类型为
int
的参数,并返回
void

如果您向foo声明的参数是指向不接受参数的函数的指针。你的意思是它应该是
void(*func)(inti)
,即使在
C
?我可以问一下为什么
C
编译器不这样问我吗?可能相关/可能重复:这是因为在C中函数不能重载。您可能仍然想用“代码> > f严格原型原型<代码>编译,以确保函数签名在任何地方都是一致的。为了比较:C的C++函数指针的等价物:<代码>空隙(*FUNC)(代码>)< /C> >(对于函数类似地,需要显式的空隙参数)。@阿空加瓜山——好点。我编辑了我的答案,将
void
作为C语言中的参数列表。
$ g++ main.cpp
main.cpp:7:39: error: too many arguments to function call, expected 0, have 1
void foo(void (*func)(), int i) {func(i);};
                                 ~~~~ ^
main.cpp:10:2: error: no matching function for call to 'foo'
        foo(bar2, 0);
        ^~~
main.cpp:7:6: note: candidate function not viable: no known conversion from 'void (int)' to 'void (*)()' for 1st argument
void foo(void (*func)(), int i) {func(i);};
     ^
2 errors generated.