我需要让 struct member 成为常规函数指针(而不是类成员函数指针)。不知道为什么编译错误。我在 Ubuntu 14.04 上运行 g++ 4.8.4。谢谢。
$ g++ te5.cc
te5.cc: In function ‘int main(int, char**)’:
te5.cc:18:9: error: invalid use of member function (did you forget the ‘()’ ?)
t.func = dum;
^
te5.cc:19:6: error: ‘func’ was not declared in this scope
(t.*func)();
代码片段
#include <stdio.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void pfpv(void *obj);
typedef struct {
pfpv func;
void *obj;
} strTimer;
void dum(void* p) {
printf("in dum()\n");
}
int main (int argc, char *argv[]) {
strTimer t;
t.func = dum;
(t.*func)();
return 0;
}
最佳答案
这可以通过使 pfpv
成为函数指针而不是函数来解决。
#include <stdio.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void (*pfpv)(void *obj);
typedef struct {
pfpv func;
void *obj;
} strTimer;
void dum(void* p) {
printf("in dum()\n");
}
int main (int argc, char *argv[]) {
strTimer t;
t.func = dum;
t.func(0);
return 0;
}
关于c++ - 结构成员字段是函数指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41365086/