为什么数据成员在 C++ 中默认是私有的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2532107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are data members private by default in C++?
提问by Naga
Is there any particular reason that all data members in a class are private by default in C++?
类中的所有数据成员在 C++ 中默认情况下都是私有的,是否有任何特殊原因?
回答by Nick Dandoulakis
The Design and Evolution of C++
2.10 The Protection Model
2.10 保护模式
Before starting work on C with Classes, I worked with operating systems. The notions of protection from the Cambridge CAP computer and similar systems - rather than any work in programming languages - inspired the C++ protection mechanisms. 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.
在开始使用类使用 C 之前,我使用过操作系统。来自剑桥 CAP 计算机和类似系统的保护概念——而不是任何编程语言的工作——启发了 C++ 保护机制。类是保护单位,基本规则是您不能授予自己访问类的权限;只有放置在类声明中的声明(假设由其所有者)才能授予访问权限。默认情况下,所有信息都是私密的。
回答by paxdiablo
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 goodthing and, like security (for example, the locking down of network services), the default should be towards good rather than bad.
封装(信息隐藏)是一个很好的东西,像安全性(例如,锁定的网络服务关闭),默认的应该朝好的而不是坏的。
回答by Ben Voigt
Because otherwise there would be no difference at all between class
and struct
?
因为否则,class
和之间根本没有区别struct
?
回答by Michael Burr
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:
. 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.
有趣的是(无论如何对我来说)是许多类定义的大括号后面的第一行是public:
. 一个类的大多数读者都对公共位感兴趣,因为那是他们与之交互的东西,无论如何,许多类定义首先有他们的公共位。
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# 让每个成员指定成员的可见性(具有合理的默认值)的技术是可取的。
回答by Barry Wark
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 可供类的客户端使用。