我想创建一个以函数指针为参数的函数。
#include <iostream>
using namespace std;
class test{
public:
test(){};
double tt(double input){
return input;
};
};
double fptr_test(double (*fptr)(double), double input){
return fptr(input);
}
int main(){
test t;
cout << t.tt(3) << endl;
cout << fptr_test(t.tt, 3) << endl; // This line doesn't work
cout << fptr_test(&test::tt, 3) << endl; // This line can't compile
return 1;
}
但它不起作用。 我如何将类成员函数作为参数传递?
不实例化可以调用成员函数吗?
最佳答案
如果要将指针传递给成员函数,则需要使用成员函数指针,而不是通用自由函数的指针和调用它的对象。
两者都不是可选的。
double fptr_test(test& t, double (test::*fptr)(double), double input){
return t.*fptr(input);
}
// call like this:
fptr_test(&test::tt, 3); // Your second try
关于c++ - 指向类成员函数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517111/