成员函数与非成员函数? [英] Member function vs. nonmember function?

查看:187
本文介绍了成员函数与非成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在类上操作的函数应该是成员函数还是非成员函数,您的规则是什么?
例如,我有一个类,它代表一个使用bools矩阵的迷宫。我正在做一个函数叫isConnected,它验证迷宫中的2点在同一区域(即可以从A到B)。



是会员还是非会员?什么是好规则?

解决方案

何时成为会员函数:




  • 当函数与类(如你的迷宫连接示例)逻辑耦合时

  • 当函数需要访问私有或受保护的成员时,



何时使其成为独立功能




  • 当它是一个泛型函数,可以模板化以自然地在其他类上工作(查看<算法>标题为好例子)


    • 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 matrix of bools. I am making a function called isConnected which verifies that 2 points in the maze are in the same region (i.e. it is possible to travel from A to B).

      Should this be member or nonmember? What is a good rule?

      解决方案

      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)

      这篇关于成员函数与非成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆