C ++类中的函数指针表 [英] Table of function pointers within a class C++
问题描述
我正在尝试在一个类中创建一个函数指针表.我还没有在网上找到任何此类示例,其中大多数涉及在其类之外使用成员函数指针.
I'm trying to make a table of function pointers within a class. I haven't been able to find any examples of this online, most involve using member function pointers outside of their class.
例如:
class Test
{
typedef void (Test::*FunctionType)();
FunctionType table[0x100];
void TestFunc()
{
}
void FillTable()
{
for(int i = 0; i < 0x100; i++)
table[i] = &Test::TestFunc;
}
void Execute(int which)
{
table[which]();
}
}test;
给我一个错误:项不求值为带有0个参数的函数".
Gives me the error "term does not evaluate to a function taking 0 arguments".
推荐答案
在 Execute
函数的这一行中:
table[which]();
您不能这样称呼它,因为它不是正常功能.您必须为其提供操作对象,因为它是成员函数的指针,而不是函数的指针(有区别):
You can't call it like that because it's not a normal function. You have to provide it with an object on which to operate, because it's a pointer to a member function, not a pointer to a function (there's a difference):
(this->*table[which])();
这将使调用对象成为 this
指针(正在执行 Execute
的那个)指针所指向的对象.
That will make the invoking object whichever object is pointed to by the this
pointer (the one that's executing Execute
).
此外,在发布错误时,请确保包括发生错误的行.
Also, when posting errors, make sure to include the line on which the error occurs.
这篇关于C ++类中的函数指针表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!