default visibility of C++ class/struct members

試著忘記壹切 提交于 2019-11-27 04:14:10

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1247745/default-visibility-of-c-class-struct-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!