如何调用指向成员函数的指针?
我收到了一个我不明白的编译错误 (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);
相关文章