【发布时间】:2021-09-10 15:17:41
【问题描述】:
在尝试在我自己的上下文中实现建议的答案 here 时,我遇到了编译错误。
考虑代码:
#include <iostream>
class SIMPLE {
public:
SIMPLE() { for (int i = 0; i < 5; i++) val[i] = 5; };
int retval(int index) { return val[index]; }
private:
int val[5];
};
void print_array_of_length5(int (*fnptr)(int index)){
for (int i = 0; i < 5; i++)
printf("%d ", fnptr(i));
}
int global_array[5] = { 0, 1, 2, 3, 4 };
int global_function(int index){
return global_array[index];
}
int main(){
print_array_of_length5(&global_function);//Works fine.
int (SIMPLE::*p)(int) = &SIMPLE::retval;//Following method suggested in the answer above
class SIMPLE smpl;
print_array_of_length5(smpl.*p);//Compile error: a pointer to a bound function may only be used to call the function
}
当提供全局函数的地址时,该函数可以工作。通过smpl.*p 时它不起作用,类似于建议的方法。应该如何解决这个错误?
【问题讨论】:
-
print_array_of_length5函数采用指向非成员函数的指针。 -
你不能在没有实例的情况下调用非
static成员函数,并且print_array_of_length5中没有可用的实例——你必须重新考虑你的整个方法
标签: c++ function-pointers member-function-pointers