如何调用指针到成员函数? [英] How do I call a pointer-to-member-function?
问题描述
我收到一个编译错误(MS VS 2008),我只是不明白。在弄乱它了很多个小时后,这一切都是模糊的,我觉得有一些非常明显(和非常愚蠢),我错过了。这里是基本的代码:
typedef int(C :: * PFN)
struct MAP_ENTRY
{
int id;
PFN pfn;
};
类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;
}
编译器声称在箭头处,term不评估为函数取1参数。为什么不? PFN作为接受一个参数的函数原型化,MAP_ENTRY.pfn是PFN。
指针到成员函数类型的指针。为了通过这样的指针调用一个函数,你需要使用操作符 - > *
或者操作符。
并提供 C
类型的对象作为左操作数。你没有。
我不知道应该在这里使用 C
只有你知道 - 但在你的例子中它可以 * this
。在这种情况下,调用可能如下
(this-> * p-> pfn)(val)
为了使它看起来稍微有点复杂,可以引入一个中间变量
PFN pfn = p-> pfn;
(this-> * pfn)(val);
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;
}
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
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.
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);
这篇关于如何调用指针到成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!