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);
这篇关于如何调用指向成员函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何调用指向成员函数的指针?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01