Member function vs. nonmember function?

后端 未结 1 1947
终归单人心
终归单人心 2021-02-15 10:13

What is your rule for which functions that operate on a class should be member functions vs. nonmember functions? For example, I have a class which represents a maze using a mat

1条回答
  •  无人共我
    2021-02-15 10:51

    When to make it a member function:

    • when the function is logically coupled with the class (like your maze connectedness example)
    • when the function needs to access private or protected members, it's better to make it a member than a friend.

    When to make it a standalone function

    • when it's a generic function that can be templatized to naturally work on other classes (look at the header for good example)

    0 讨论(0)
提交回复
热议问题