C.8: Use class rather than struct if any member is non-public
C.8:存在非公有成员时,使用class而不是struct定义类
Reason(原因)
Readability. To make it clear that something is being hidden/abstracted. This is a useful convention.
可读性。明确有些东西是被隐藏或抽象的。这是一个有用的惯例。
Example, bad(反面示例)
struct Date {
int d, m;
Date(int i, Month m);
// ... lots of functions ...
private:
int y; // year
};
There is nothing wrong with this code as far as the C++ language rules are concerned, but nearly everything is wrong from a design perspective. The private data is hidden far from the public data. The data is split in different parts of the class declaration. Different parts of the data have different access. All of this decreases readability and complicates maintenance.
如果只是考虑C++语言的规则,这段代码没有任何错误。但是如果从设计的观点来看的话,差不多所有东西都错了。私有数据被也隐藏在距离共有数据很远的位置。数据被分散到类声明的不同部分。不同部分的数据的访问属性也不同。所有的这些都会降低可读性并增加维护的复杂性。
Note(注意)
Prefer to place the interface first in a class, see NL.16.
类的最初最好放置接口(这里值共有成员函数,译者注),参见NL.16.
链接:https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rl-order
Enforcement(实施建议)
Flag classes declared with struct if there is a private or protected member.
如果使用struct关键字声明的类具有私有或保护成员,进行提示。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c8-use-class-rather-than-struct-if-any-member-is-non-public
觉得本文有帮助?请分享给更多人。
更多更新文章,欢迎关注微信公众号【面向对象思考】
面向对象设计,面向对象编程,面向对象思考!
本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.sosokankan.com/article/1419771.html