Member function vs. nonmember function?

后端 未结 2 1453
孤街浪徒
孤街浪徒 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 header for good example)

提交回复
热议问题