指向成员函数的指针,而不是函数指针

C++ pointer to member function not a function pointer

本文关键字:函数 指针 成员      更新时间:2023-10-16

假设我有以下定义:

class ScriptInterpreter {
public:
class cell;
typedef ScriptInterpreter::cell (ScriptInterpreter::*proc_t) (const std::vector<cell> &);
class cell {
public:
  proc_t proc;
};
ScriptInterpreter::cell proc_add(const std::vector<cell> & c);
};

和下面的代码:

ScriptInterpreter::eval(ScriptInterpreter::cell cell, environment * env)
{
// ...
ScriptInterpreter::cell c;
c.proc = &ScriptInterpreter::proc_add;
return (c.*proc_)(exps);
}

在我试图调用函数指针的那行,我得到了错误

error: called object type 'proc_t' (aka 'ScriptInterpreter::cell (ScriptInterpreter::*)(const std::vector<cell> &)') is not
  a function or function pointer

当我在函数前面添加*时,这一行看起来像这样:

ScriptInterpreter::cell c = (proc_cell.*proc_)(exps);

生成如下:

error: use of undeclared identifier 'proc_'

我已经看了c++中的回调函数和其他类似的问题,但没有什么能真正给我提示什么是错的或提供任何关于我的错误的信息。我绝对不会有任何名字重复或类似的东西。另外,在阅读了什么是未声明的标识符错误以及如何修复它之后,我很确定我得到了一切都好。

我做错了什么?

编辑:用实际代码而不是占位符代码更新代码

为了通过指针到成员类型的指针调用成员函数,必须使用操作符.*或操作符->*。在左侧,您必须指定要调用该成员函数的对象。

在您的例子中,尝试这样做可能如下所示

A::B b_object;
b_object.func = &A::func_to_call;
A a_object;
A::B other_b_object = (a_object.*b_object.func)();

注意,由于指针被声明为指向A的成员,所以.*操作符的左侧需要一个A类型的对象。

然而,在您的特定情况下,这是错误的,因为b_object.func是私有的,不能从main访问。

注:int main,不是void main