数组中struct中的c++成员函数指针给出编译错误

标签 c++ arrays function-pointers

我有这段定义结构的代码(传入的是简单的结构)

#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/

相关文章:

javascript - 将此 javascript 对象从 jQuery 传递到 PHP?

c++ - print 函数中的 for(auto) 循环抛出错误,为什么?

c++ - 是否可以在运行时替换方法?

c++ - 函数指针的现代 C++ 替代品

c++ - 内部函数被识别为指针

c++ - QThread::wait() 不使用直接连接不返回

c++ - 自定义 win32 拖放,无法更改无效(斜线圆圈)光标

C++二叉搜索树去除段错误

C++ 如何从没有共享父类(super class)的类中调用公共(public)方法?

arrays - Swift:将组号分配给元组数组中的元组成员