c++ - 指向类成员函数的函数指针

标签 c++

我想创建一个以函数指针为参数的函数。

#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/

相关文章:

c++ - 带有模板参数的自定义 C++ 异常

c++ - 对比较函数

C++ 麻烦的析构函数

C++ Set 迭代器没有到达 Set 的末尾

c++ - 为什么 HDF5 Output Caffe 层会写入看似不正确维度的数据?

c++ - FindWindow() 通过不完整的名称

c++ - 如何用qt分发代码?

python - pybind11 STL 自动转换器破坏 std::list 指针

c++ - 如何在 C++ 中使用 PI 常量

c++ - 二叉树 C++ 基础