`
kuwoleft
  • 浏览: 1068370 次
文章分类
社区版块
存档分类
最新评论

宁以non-member-and-non-friend替换member函数——effective c++学习笔记

 
阅读更多

宁以non-member-and-non-friend替换member函数(Prefer non-member non-friend function to member functions.

non-member-and-non-friend表示非成员且非友元。

之所以这样做,是为了减少能够访问private成员的代码的数量,以此来提高封装性。

namespace的使用

<!--[if !supportLists]-->1、 <!--[endif]-->namespace的定义可以累加。

<!--[if !supportLists]-->2、 <!--[endif]-->namespace既可以包含声明,也可以包含定义。

<!--[if !supportLists]-->3、 <!--[endif]-->对于namespace内函数,变量的引用,如果在namespace内,则可以直接使用函数名。如果在namespace外,则要需要使用name::的方式引用。在局部命名空间内,如果和全局命名空间重名,则不加修饰的话引用的是局部。直接加“::”则表示使用的是全局的命名空间。定义是可以在变量和函数前加上命名空间的限定,则可以使用此命名空间的所有的函数。如果没有声明而直接定义,则不可以。

<!--[if !supportLists]-->4、 <!--[endif]-->嵌套命名空间:使用的时候:name1::name2::value;

<!--[if !supportLists]-->5、 <!--[endif]-->一个Type首先在其所在的嵌套命名空间查找什么,然后上层命名空间查找,最后在全局空间查找。

<!--[if !supportLists]-->6、 <!--[endif]-->为命名命名空间和static修饰函数类似。

<!--[if !supportLists]-->7、 <!--[endif]-->名字空间别名,using声明,using指示符

<!--[if !supportLists]-->8、 <!--[endif]-->别名:namespace IBM = Inink_business_machine

<!--[if !supportLists]-->9、 <!--[endif]-->using声明可以在其声明的域中以简短的名字调用。

<!--[if !supportLists]-->10、 <!--[endif]-->using指示符运行我们让来自特定名字空间的所有名字已简单的名字可见。

注意两个问题:

<!--[if !supportLists]-->1、 <!--[endif]-->是在member函数和non-member-and-non-friend函数间作出选择。

<!--[if !supportLists]-->2、 <!--[endif]-->虽然不可以是members函数,但可以是其他classmember

至于这样做的机能扩充性,是由namespace来实现的。

比如,对于有些便利函数来说,可能一个class会非常多,那么对其进行分类,并且声明在不同的头文件中,同时也定义在一个namespace中。如果需要扩展,则直接在不同的头文件中声明即可。这一点和我在做网管代理时,我的card类就有相当多的这样的函数。

注意:

1、宁以non-member-and-non-friend函数替换member函数,这样做可以增加封装性,包裹性和机能扩充性。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics