C++ Passing pointer to non-static member function

前端 未结 2 701
忘掉有多难
忘掉有多难 2021-01-23 09:28

Hi everyone :) I have a problem with function pointers
My \'callback\' function arguments are:
1) a function like this: int(*fx)(int,int)
2) an int variable: int a<

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 09:50

    I would do it with std functors, here is a simple example based off of your code:

    #include 
    #include 
    using namespace std;
    
    class A{
    private:
        int x;
    public:
        A(int elem){
            x = elem;
        }
    
        static int add(int a, int b){
            return a + b;
        }
    
        int sub(int a, int b) const{
            return x - (a + b);
        }
    };
    
    void callback( std::function fx, A obj, int a, int b)
    {
        cout << "Value of the callback: " << fx( obj, a, b) << endl;
    }
    
    int main()
    {
    A obj(5);
    
    
        std::function Aprinter= &A::sub;
    
        callback(Aprinter,obj,1,2);
    }
    

提交回复
热议问题