如何调用成员函数指针?
我收到一个我不明白的编译错误(MS VS 2008)。经过几个小时的混乱之后,一切都变得模糊了,我觉得有一些非常明显(而且非常愚蠢)的东西我错过了。这是基本代码:
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。我在这里缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是为了配合我自己的经验,我在 g++ 中遇到了由以下语句引起的错误:
其中 stateHandler 是指向 *this 引用的类的 void 成员函数的指针。该问题是由箭头运算符之间的空格引起的。以下代码片段可以正常编译:
我正在使用 g++ (GCC) 4.4.2 20090825(预发布)。 FWIW。
Just to chime in with my own experience, I've come across an error in g++ caused by this statement:
Where stateHandler is a pointer to a void member function of the class referenced by *this. The problem was caused by the spaces between the arrow operator. The following snippet compiles fine:
I'm using g++ (GCC) 4.4.2 20090825 (prerelease). FWIW.
p->pfn 是函数指针。您需要使用 * 才能使其发挥作用。更改为
p->pfn is a function pointer. You need to use * to make it function. Change to
p->pfn
是成员函数指针类型的指针。为了通过这样的指针调用函数,您需要使用运算符->*
或运算符.*
并提供类型为C
的对象code> 作为左操作数。你没有。我不知道这里应该使用哪个
C
类型的对象 - 只有你知道 - 但在你的示例中它可能*this.在这种情况下,调用可能如下所示
为了使其看起来不那么复杂,您可以引入一个中间变量
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 typeC
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 followsIn order to make it look a bit less convoluted, you can introduce an intermediate variable
尝试
Try