以下是在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);
}
它与
$gcc main.c
是的。
下面是我尝试将它迁移到C++:
#include <cstdio>
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++?