我有这段定义结构的代码(传入的是简单的结构)
#define FUNCS_ARRAY 3
struct func
{
void (AA::*f) (incoming *);
int arg_length;
};
func funcs[FUNCS_ARRAY];
然后在 AA 类主体中,我这样定义指针数组:
funcs[0] = { &AA::func1, 4 };
funcs[1] = { &AA::func2, 10 };
funcs[2] = { &AA::func2, 4 };
当我尝试通过数组调用其中一个函数时出现编译错误:
如果我这样调用它(p 是传入的):
(*funcs[p->req]->*f)(p);
我收到这个错误:
error: no match for ‘operator*’ in ‘*((AA*)this)->AA::funcs[((int)p->AA::incoming::req)]’
当我尝试这样调用它时:
(funcs[p->req]->*f)(p);
我得到:
error: ‘f’ was not declared in this scope
当我尝试这个时:
(funcs[p->req].f)(p);
error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f (...)’, e.g. ‘(... ->* ((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f) (...)’
访问结构内部函数指针的正确方法是什么?
最佳答案
要通过指向成员函数的指针调用成员函数,您需要该指针和相应类的实例。
在你的例子中,指向成员的指针是 funcs[i].f
,我假设你有一个名为 的
。然后你可以像这样调用这个函数:AA
实例一个
(aa.*(funcs[p->req].f))(p);
如果 aa
是指向 AA 的指针,则语法为:
(aa->*(funcs[p->req].f))(p);
如果您从 AA
的(非静态)成员函数中调用,请尝试:
(this->*(funcs[p->req].f))(p);
关于数组中struct中的c++成员函数指针给出编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592960/