Cast pointer to member function to normal pointer

前端 未结 6 616
抹茶落季
抹茶落季 2020-11-28 15:52

Currently I have a class of this kind, shortened for simplicity:

class MyClass {
    public: 
        MyClass();
        void* someFunc(void* param);
}
         


        
6条回答
  •  渐次进展
    2020-11-28 16:36

    See this sample:

    #include 
    
    class MyClass 
    {
    public: 
        MyClass()
        {
        }
    
        void* someFunc(void* param)
        {
            std::cout << "someFunc" << std::endl;
            return (void*)0;
        }
    };
    
    typedef void* (MyClass::*MemFun)(void*);
    
    void secondFunc(int a, int b, MemFun fn)
    {
        MyClass* ptr = 0;
        // This is dangerous! If the function someFunc do not operate the data in the class.
        // You can do this.
        (ptr->*fn)(0);
        std::cout << "Call me successfully!" << std::endl;
    }
    
    int main()
    {
        secondFunc(1, 2, &MyClass::someFunc);
    
        system("pause");
    
        return 0;
    }
    

提交回复
热议问题