当前位置:主页 > 查看内容

C++病历:setting limits

发布时间:2021-09-27 00:00| 位朋友查看

简介:setting limits(访问限制 (栗子privatepublicprotected) 即为在类中那些成员可以被别人访问哪些只能由自己访问。 to keep the client programmer’s hands off members they shouldn’t touch to allow the library designer to change the internal working……

setting limits(访问限制)

(栗子:private,public,protected)
即为在类中那些成员可以被别人访问,哪些只能由自己访问。
to keep the client programmer’s hands off members they shouldn’t touch
to allow the library designer to change the internal workings of structure without worrying about how it will affect the client programmer

C++访问属性:

1.public
任何人都可以访问
2.private
仅有class下的成员函数可以访问class中的variables或者function(main主函数也不可以,仅在一个class中,而不是.cpp中)
同一个class中不同的的成员函数之间是可以彼此访问彼此变量的
仅在编译时刻提醒你有没有访问别人私有的东西。
attention:C++的OOP特性仅在源代码下,编译过后就不是OOP的东西啦
3.protected
只有这个类自己或者它的子类以及再子类(子子孙孙,无穷无尽。。。)

C++中破坏OOP特性的还有一个东西叫Friend

它的用法是declare别人是你的friend,从而访问你私有的东西,这个别人可以是class,function,class中的function。
但你不可以声明你是别人的friend来访问别人私有的东西,这样就太犯规啦!
(就好像我说你是我的好朋友,我女朋友就是你女朋友,但我不可以说你是我的好朋友,所以你女朋友就是我女朋友,这样就合理多啦(憨憨笑))
栗子:

struct X;//这里是一个前向声明,是一个不完整的类的定义,仅仅为了后面的编译能够通过
struct Y{
	void f(X*);} //Y中的X便对X有访问权限
struct X{  //definition:从这里开始定义我们的struct X也不迟
privateint i;
public:
	void initialize();
	friend void g(X*,int); //global friend
	friend void Y::(X*); //struct member friend
	friend struct Z; //entire stuct is a friend
	friend void h();
};

tips:
1.某些operator的重载是要以friend授权的
2.一个类已经写好了就无法再对其friend了
3.friend的授权是在编译中处理的

这里提到一点class与struct在C++中细微的差别:

如果,你在类里面有没有声明访问属性的地方**,struct对未声明的地方全部为public。**除非你的类特别简单,否则我们一般首选class。

;原文链接:https://blog.csdn.net/m0_53328774/article/details/116070687
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐