简体   繁体   English

为什么数据成员默认在C ++中是私有的?

[英]Why are data members private by default in C++?

在C ++中,默认情况下,类中的所有数据成员是否都是私有的?

The Design and Evolution of C++ C ++的设计与演变

2.10 The Protection Model 2.10保护模式

Before starting work on C with Classes, I worked with operating systems. 在开始使用Classes进行C工作之前,我使用过操作系统。 The notions of protection from the Cambridge CAP computer and similar systems - rather than any work in programming languages - inspired the C++ protection mechanisms. 剑桥CAP计算机和类似系统的保护概念 - 而不是编程语言中的任何工作 - 启发了C ++保护机制。 The class is the unit of protection and the fundamental rule is that you cannot grant yourself access to a class; 班级是保护的单位,基本原则是你不能授予自己访问课程的权利; only the declarations placed in the class declaration (supposedly by its owner) can grant access. 只有放在类声明中的声明(据称由其所有者)才能授予访问权限。 By default, all information is private. 默认情况下,所有信息都是私有的。

Because it's better to be properly encapsulated and only open up the things that are needed, as opposed to having everything open by default and having to close it. 因为最好是正确封装并且只打开所需的东西,而不是默认打开所有东西并且必须关闭它。

Encapsulation (information hiding) is a good thing and, like security (for example, the locking down of network services), the default should be towards good rather than bad. 封装(信息隐藏)是一件好事 ,像安全性(例如,锁定的网络服务关闭),默认的应该朝好的而不是坏的。

因为否则classstruct之间根本没有区别?

The reasoning is that the public parts of a class should be explicitly made public. 理由是,一个班级的公共部分应该明确公开。

The interesting thing about this (to me anyway) is that the first line after the opening brace of many, many class definitions is public: . 关于这一点的有趣之处(无论如何)是在许多类定义的开头大括号之后的第一行是public: Most readers of a class are interested in the public bits, since that's what they interact with, and so many class definitions have their public bits first anyway. 一个类的大多数读者都对公共位感兴趣,因为这是他们与之交互的内容,所以很多类定义都有他们的公共位。

C++'s access specifiers apply to the range that follows them - I think Java and C#'s technique of having each member to specify the visibility of the member (with a sensible default) is preferable. C ++的访问说明符适用于它们之后的范围 - 我认为Java和C#的技术是让每个成员指定成员的可见性(具有合理的默认值)是可取的。

In a word, encapsulation. 总之,封装。 The goal is to have private implementation details (such as data members) be private. 目标是将私有实现细节(例如数据成员)设为私有。 Only explicitly public API is made available to clients of the class. 只有明确的公共API可供该类的客户使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM