Virtual Methods or Function Pointers

后端 未结 8 1468
春和景丽
春和景丽 2020-12-07 11:31

When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback c

8条回答
  •  星月不相逢
    2020-12-07 12:34

    Function pointers are more C-style I would say. Mainly because in order to use them you usually must define a flat function with the same exact signature as your pointer definition.

    When I write C++ the only flat function I write is int main(). Everything else is a class object. Out of the two choices I would choose to define an class and override your virtual, but if all you want is to notify some code that some action happened in your class, neither of these choices would be the best solution.

    I am unaware of your exact situation but you might want to peruse design patterns

    I would suggest the observer pattern. It is what I use when I need to monitor a class or wait for some sort of notification.

提交回复
热议问题