Why would one use function pointers to member method in C++?

前端 未结 10 2188
情书的邮戳
情书的邮戳 2021-02-10 23:48

A lot of C++ books and tutorials explain how to do this, but I haven\'t seen one that gives a convincing reason to choose to do this.

I understand very well why functio

10条回答
  •  面向向阳花
    2021-02-11 00:28

    Here is a typical scenario we have here. We have a notification framework, where a class can register to multiple different notifications. When registering to a notification, we pass the member function pointer. This is actually very similar to C# events.

    class MyClass
    {
        MyClass()
        {
            NotificationMgr::Register( FunctionPtr( this, OnNotification ) );
        }
        ~MyClass()
        {
            NotificationMgr::UnRegister( FunctionPtr( this, OnNotification ) );
        }
    
        void OnNotification( ... )
        {
            // handle notification
        }
    };
    

提交回复
热议问题