这个问题和我想做的很相似Calling C++ member function pointer from a struct . 然而,我的结构包含一个成员函数指针,该指针在另一个类中定义,然后是定义和使用该结构的类。下面是一些示例代码,说明我的类、结构和函数指针的布局方式。
// Alpha.h:
class Alpha{
public:
void function1(char name[], int number);
void function2(char name[], int number);
void function3(char name[], int number);
typedef void (Alpha::*My_func_ptr)(char name[], int number);
static My_func_ptr functionTable[];
};
// Alpha.cpp:
#include "Alpha.h"
Alpha::My_func_ptr Alpha::functionTable[] = {
&Alpha::function1,
&Alpha::function2,
&Alpha::function3
};
void Alpha::function1(char name[], int number)
{
//some stuff
}
void Alpha::function2(char name[], int number)
{
//some stuff
}
void Alpha::function3(char name[], int number)
{
//some stuff
}
// Beta.h:
#include "Alpha.h"
typdef struct{
char bName[10];
Alpha::My_func_ptr fptr;
}ptr_structure;
class Beta{
public:
void betafunction();
Alpha alphaobject;
ptr_structure str_array[3];
};
// Beta.cpp:
#include "Beta.h"
void betafunction()
{
str_array[0].fptr = alphaobject.functionTable[0];
str_array[1].fptr = alphaobject.functionTable[1];
str_array[2].fptr = alphaobject.functionTable[2];
(str_array[0].fptr)("name", 1); //gives error expression must have
//(pointer-to-) function type
(this->*str_array[0].fptr)("name", 1);
//error pointer-to-member selection class types are incompatible "Beta" and "Alpha"
//sample function pointer call using function table from other class,
//this syntax compiles and runs without error.
(alphaobject.*Alpha::functionTable[0]("name", 1);
}
如您所见,我可以从数组调用函数指针,但似乎无法弄清楚如何从结构数组内部调用函数指针。
最佳答案
通过成员函数指针调用时,需要有一个与该指针关联的对象实例:
(alphaobject.*(str_array[0].fptr))("name", 1)
^^^^^^^^^^^
关于c++ - 在 C++ 中调用作为结构数组成员的成员函数指针的语法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9675104/