Member function vs. nonmember function?

后端 未结 2 1447
孤街浪徒
孤街浪徒 2021-02-15 10:34

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

相关标签:
2条回答
  • 2021-02-15 11:03

    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 <algorithms> header for good example)
    0 讨论(0)
  • 2021-02-15 11:17

    Herb Sutter says "we want to make them nonmember nonfriends if reasonably possible", and he's smarter than I am.

    http://www.gotw.ca/gotw/084.htm

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