C++ 的默认可见性 类/结构成员
在 C++ 中,为什么类成员的默认可见性是 private,而结构的默认可见性是 public?
In C++, why is private the default visibility for members of classes, but public for structs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++ 是作为 C 的超集引入的。结构体是从 C 继承而来的,其中其成员的语义是
public
的语义。 存在大量 C 代码,包括需要与 C++ 一起使用的使用结构的库。类是在 C++ 中引入的,为了符合 OO 封装哲学,它们的成员默认是
private
。C++ was introduced as a superset of C. Structs were carried over from C, where the semantics of their members was that of
public
. A whole lot of C code exists, including libraries that were desired to work with C++ as well, that use structs.Classes were introduced in C++, and to conform with the OO philosophy of encapsulation, their members are
private
by default.因为类是面向对象的常用方法,这意味着成员变量应该是私有的并且具有公共访问器 - 这对于创建 低耦合。 另一方面,结构必须与 C 结构兼容,C 结构始终是公共的(C 中没有公共和私有的概念),并且不使用访问器/修改器。
Because a class is a usual way of doing object orientation, which means that member variables should be private and have public accessors - this is good for creating low coupling. Structs, on the other hand, have to be compatible with C structs, which are always public (there is no notion of public and private in C), and don't use accessors/mutators.
可能是为了向后兼容 C 结构。 这样,在 C 代码中声明的结构在 C++ 代码中使用时将继续以相同的方式工作。
Probably for backwards compatibility with C structs. This way structs declared in C code will continue to work the same way when used in C++ code.