C++ 类/结构成员的默认可见性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1247745/
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
default visibility of C++ class/struct members
提问by S I
In C++, why is private the default visibility for members of classes, but public for structs?
在 C++ 中,为什么类成员的默认可见性是私有的,而结构是公共的?
回答by Oren Trutner
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 继承而来的,其成员的语义是公共的。存在大量 C 代码,包括希望与 C++ 一起使用的库,它们使用结构。类是在 C++ 中引入的,为了符合 OO 的封装哲学,它们的成员默认是私有的。
回答by a_m0d
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 中没有公共和私有的概念),并且不使用访问器/修改器。
回答by Karl Voigtland
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.
可能是为了与 C 结构向后兼容。这样,在 C 代码中声明的结构体在 C++ 代码中使用时将继续以相同的方式工作。