前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.8:存在非公有成员时,使用class而不是struct定义类

C++核心准则C.8:存在非公有成员时,使用class而不是struct定义类

作者头像
面向对象思考
发布2020-03-25 15:54:20
4330
发布2020-03-25 15:54:20
举报

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

觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。


面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.8: Use class rather than struct if any member is non-public
    • Reason(原因)
      • Example, bad(反面示例)
        • Note(注意)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档