成员函数如何做回调函数---------------------详解 (读mfc源码得来)

成员函数如何做回调函数---------------------详解 (读mfc源码得来)

class parent
{
public:
    typedef void (parent:: *pfn) ();
    parent() : m_p(this)
    {
    }
    virtual ~parent(){}

    void prints()
    {
        std::cout << "parent!" << std::endl;
    }
 
    void setcallback(pfn pf)
    {
        m_pfn = pf;
        (this->*m_pfn)();                                                 //回调,输出child!
    }

    pfn m_pfn;
 };


class child : public parent
{
public:
    child()
    {
        m_pfn = static_cast<void (parent::*)()>(prints);    //这里类型必须匹配(利用static_cast)
    }
    ~child(){}

    void prints()
    {
        std::cout << "child!" << std::endl;
    }

    void _callback()
    {
        (this->*m_pfn)();                                            //回调,输出child!
  
        setcallback(m_pfn);

    }
    int a;
    pfn m_pfn;
};

void main()
{
    parent *pt;
    child onechild;
    pt = &onechild;
 
    onechild._callback();
}

你可能感兴趣的:(成员函数如何做回调函数---------------------详解 (读mfc源码得来))