C++ 的默认可见性 类/结构成员

发布于 2024-08-01 17:47:43 字数 55 浏览 5 评论 0原文

在 C++ 中,为什么类成员的默认可见性是 private,而结构的默认可见性是 public?

In C++, why is private the default visibility for members of classes, but public for structs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

书信已泛黄 2024-08-08 17:47:43

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.

慢慢从新开始 2024-08-08 17:47:43

因为类是面向对象的常用方法,这意味着成员变量应该是私有的并且具有公共访问器 - 这对于创建 低耦合。 另一方面,结构必须与 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.

违心° 2024-08-08 17:47:43

可能是为了向后兼容 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文