前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.3:用类表现接口和实现的区别

C++核心准则C.3:用类表现接口和实现的区别

作者头像
面向对象思考
发布2020-03-25 15:52:01
4280
发布2020-03-25 15:52:01
举报
文章被收录于专栏:C++核心准则原文翻译

C.3: Represent the distinction between an interface and an implementation using a class

C.3:用类表现接口和实现的区别

Reason(原因)

An explicit distinction between interface and implementation improves readability and simplifies maintenance.

明确地区分接口和实现可以提高可读性并简化维护工作。

Example(示例)

代码语言:javascript
复制
class Date {
public:
    Date();
    // validate that {yy, mm, dd} is a valid date and initialize
    Date(int yy, Month mm, char dd);

    int day() const;
    Month month() const;
    // ...
private:
    // ... some representation ...

};

For example, we can now change the representation of a Date without affecting its users (recompilation is likely, though).

例如,上述代码中我们可以修改Data的实现而不影响使用者(虽然可能需要重新编译)。

译者注:这个例子应该没有提供完整的代码,因此作者的想法没有完全表达清楚。Data的代码应该遵循以下原则:public部分只用于声明Data的接口,而private部分用于Data的具体实现,包括私有成员函数。成员的访问权限根据是接口还是实现决定,而不是其他。

Note(注意)

Using a class in this way to represent the distinction between interface and implementation is of course not the only way. For example, we can use a set of declarations of freestanding functions in a namespace, an abstract base class, or a template function with concepts to represent an interface. The most important issue is to explicitly distinguish between an interface and its implementation "details." Ideally, and typically, an interface is far more stable than its implementation(s).

这样使用类表现接口和实现的区别当然不是唯一的方式。例如我们可以使用某个命名空间中一组独立的函数,一个抽象基类,或者用于表现接口的包含concept参数的模板函数。最重要的是在接口和具体实现之间进行明确地区分。理想情况下,也是一般情况下,接口都会比实现更稳定。

译者注:concept是C++引入的新特性。

Enforcement(实施建议)

???

英文原文地址:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c3-represent-the-distinction-between-an-interface-and-an-implementation-using-a-class

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

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

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


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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.3: Represent the distinction between an interface and an implementation using a class
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档