指向成员函数的指针,而不是函数指针
C++ pointer to member function not a function pointer
假设我有以下定义:
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
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针