Heath's Blog

There is no end, it is just the beginning! - A Game Developer's Notes

C++认知误区(1):成员保护机制

    C++将struct/class的成员保护粒度划分为:public、protected、private,这在语言入门时就应知晓的。然而前几天遇到的一段代码,却让我琢磨了许久:

class Record
{
public:
	Record& operator= (const Record& r)
	{
        	file = r.file;
		offset = r.offset;
		return *this;
	}
	...
private:
	unsigned char *offset;
	NBFile &file;
		...
};

    为什么作为private成员的offset和file可以直接通过成员访问运算符访问?

    我开始意识到自己对成员保护机制的认识有误,不知从什么时候起"对象.私有成员"的模式在大脑中就被一票否定了,这意味着默认了成员保护机制是针对对象的。然而,"The Annotated C++ Reference Manual"对保护机制的精辟总结:

(1) Protection is provided by compile-time mechanisms against accident, not against fraud or explicit violation.
(2) Access is granted by a class, not unilaterally taken.
(3) Access control is done for names and does not depend on the type of what is named.
(4) The unit of protection is the class, not the individual object.
(5) Access is controlled, not visibility

明确指出成员保护机制是针对类的,且为编译时机制。仔细一想,C++从来就未有在运行时检查成员访问合法性的机制,所有的检查都在编译期完成,此时根本不会产生对象,因而之前对该机制的认知是有问题的。BTW,第一点总结得甚好,运行时可通过私有成员指针在外部访问的原因应该很清楚了吧(这被认为是fraud,:P)。

   生活、工作中会有各种各样认知误区,与自己认知相悖的,不一定是错误的,要搜寻客观证据,理性思考。

posted on 2010-04-24 16:16 Heath 阅读(2438) 评论(3)  编辑 收藏 引用 所属分类: Programming LanguageStudying

Feedback

# re: C++认知误区(1):成员保护机制 2010-04-25 16:50 guest

Record& operator= (const Record& r);

是Redcord的成员, 当然可以访问 Record 的私有成员
  回复  更多评论   

# re: C++认知误区(1):成员保护机制[未登录] 2010-04-26 16:43 12

编译器的行为吧。我一直是GET SET出身的。。。  回复  更多评论   

# re: C++认知误区(1):成员保护机制 2010-05-19 22:02 dtzleg

因为是在Record类内部函数
如果是友元函数,也可以

否则根本通不过编译的

不过,在模板里倒是有混过编译期却在执行期访问违例的  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理