assign a member function to a function pointer

前端 未结 3 535
小鲜肉
小鲜肉 2021-01-27 22:44

If I have two classes like this :

class A
{
    public:
        int *(*fun)( const int &t );
        A( int *( *f )( const int &t ) ) : fun( f ) {}
};
         


        
3条回答
  •  无人及你
    2021-01-27 23:09

    Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the std::function. It only has been available since C++11. If you cannot use it, try looking on Boost's Implementation.

    I can give you an example of how to use the std::function:

    bool MyFunction(int i)
    {
        return i > 0;
    }
    
    std::function funcPointer = MyFunction;
    

    Using this you will drastically improve your code reliability. As of your problem, specifically:

    class A
    {
    public:
        std::function fun;
        A(std::function f) : fun(f) {}
    };
    
    class B
    {
    private:
        float r;
        int *f(const int &t)
        {
            return new int(int(r) + t);
        }
        A *a;
        B()
        {
    
            std::function tempFun = std::bind(&B::f, this, _1);
            a = new A(tempFun);
        }
    };
    

    You have to add the following namespace:

    using namespace std::placeholders;
    

提交回复
热议问题