Non-member non-friend functions vs private functions

前端 未结 4 954
情歌与酒
情歌与酒 2020-12-31 06:42

Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods

4条回答
  •  情话喂你
    2020-12-31 07:23

    Not all private methods should be moved to non-member non-friend function, but those that do not need access to your private data members should be. You should give access to as little function as you can, to encapsulate your classes as mush a possible.

    I strongly recommend reading Effective C++ from Scott Meyers which explain why you should do this and when it is appropriate.

    Edit : I would like to add that this is less true for private method then for public ones, although still valid. As encapsulation is proportionnal to the amount of code you would break by modifying your method, having a private member-function , even though it does not requires access to data members. That is because modifying that code would break little code and only code that you have control over.

提交回复
热议问题