class
rather than struct
if any member is non-publicC.8:存在非公有成员时,使用class而不是struct定义类
Readability. To make it clear that something is being hidden/abstracted. This is a useful convention.
可读性。明确有些东西是被隐藏或抽象的。这是一个有用的惯例。
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++语言的规则,这段代码没有任何错误。但是如果从设计的观点来看的话,差不多所有东西都错了。私有数据被也隐藏在距离共有数据很远的位置。数据被分散到类声明的不同部分。不同部分的数据的访问属性也不同。所有的这些都会降低可读性并增加维护的复杂性。
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
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
有任何疑问,欢迎留言提问或讨论。
面向对象开发,面向对象思考!