专业的编程技术博客社区

网站首页 > 博客文章 正文

public成员定义接口,private成员负责实现

baijin 2024-10-12 02:10:05 博客文章 13 ℃ 0 评论

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


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

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表