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

面向对象思考

共 1725字,需浏览 4分钟

 · 2019-12-09

0fb3a1a1cf6979849810e9556d6f1302.webp

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(示例)
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


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

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

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




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

浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报