assign a member function to a function pointer

前端 未结 3 533
小鲜肉
小鲜肉 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 22:56

    this result in compiler error

    Because f is a A's non-static member function returning int*, that accepts single const reference to int. That means, that its type is not:

    int* (*)(const int &);
    

    but:

    int* (A::*)(const int&);
    

    Also, your code signalizes very bad design - I think you need simple virtual function. But if you want to keep writing things this way, you may want to read: ISOCPP: Pointers to members.

    Remember, that non-static member functions of type C always accepts additional implicit argument of type C* (or const C*, if function is declared with const qualifier), that points to instance of C this function was called on.

提交回复
热议问题