How do I call a pointer-to-member-function?(如何调用指向成员函数的指针?)
问题描述
我收到了一个我不明白的编译错误 (MS VS 2008).搞了好几个小时之后,一切都变得模糊了,我觉得我错过了一些非常明显(而且非常愚蠢)的东西.这是基本代码:
I'm getting a compile error (MS VS 2008) that I just don't understand. After messing with it for many hours, it's all blurry and I feel like there's something very obvious (and very stupid) that I'm missing. Here's the essential code:
typedef int (C::*PFN)(int);
struct MAP_ENTRY
{
int id;
PFN pfn;
};
class C
{
...
int Dispatch(int, int);
MAP_ENTRY *pMap;
...
};
int C::Dispatch(int id, int val)
{
for (MAP_ENTRY *p = pMap; p->id != 0; ++p)
{
if (p->id == id)
return p->pfn(val); // <--- error here
}
return 0;
}
编译器在箭头处声称术语不会评估为采用 1 个参数的函数".为什么不?PFN 的原型是一个带一个参数的函数,而 MAP_ENTRY.pfn 是一个 PFN.我在这里错过了什么?
The compiler claims at the arrow that the "term does not evaluate to a function taking 1 argument". Why not? PFN is prototyped as a function taking one argument, and MAP_ENTRY.pfn is a PFN. What am I missing here?
推荐答案
p->pfn
是指向成员函数类型的指针.为了通过这样的指针调用函数,您需要使用运算符 ->*
或运算符 .*
并提供 C类型的对象code> 作为左操作数.你没有.
p->pfn
is a pointer of pointer-to-member-function type. In order to call a function through such a pointer you need to use either operator ->*
or operator .*
and supply an object of type C
as the left operand. You didn't.
我不知道应该在这里使用哪种 C
类型的对象 - 只有你知道 - 但在你的例子中它可能是 *这个
.在这种情况下,调用可能如下所示
I don't know which object of type C
is supposed to be used here - only you know that - but in your example it could be *this
. In that case the call might look as follows
(this->*p->pfn)(val)
为了让它看起来不那么复杂,可以引入一个中间变量
In order to make it look a bit less convoluted, you can introduce an intermediate variable
PFN pfn = p->pfn;
(this->*pfn)(val);
这篇关于如何调用指向成员函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何调用指向成员函数的指针?
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01