C++核心准则C.2:包含不变式时用class,否则用struct定义类

面向对象思考

共 2269字,需浏览 5分钟

 · 2019-12-08


ccc694d1dcd87dd4e57083394e69f27c.webp

C.2: Use class if the class has an invariant; use struct if the data members can vary independently

C.2:类包含不变式是使用class定义类,如果数据成员可以独立变更时使用struct定义类。


译者注:不变式可以认为是类的成员必须满足的条件。例如对于std::string来说,长度成员必须等于其管理的字符串长度。

Reason(原因)

Readability. Ease of comprehension. The use of class alerts the programmer to the need for an invariant. This is a useful convention.

可读性。降低理解难度。使用class关键字让程序员意识到需要不变式。这是一个有用的惯例。

译者注:使用class关键字还默认保证了数据成员不会被随意修改,这使维持不变式成为可能。

Note(注意)

An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.

不变式是一个对象的成员必须满足的逻辑条件,这些条件由构造函数建立,是public成员函数的前提条件。一旦不变式成立(通常是由构造函数),该对象所有成员函数都可以被调用。不变式可以被非正式的说明(例如通过注释),或者通过Expects(事前条件)正式检查。

If all data members can vary independently of each other, no invariant is possible.

如果所有数据成员都可以相互独立地变更,则不可能存在不变式。

Example(示例)
struct Pair {  // the members can vary independently    string name;    int volume;
};

but:

class Date {public:    // validate that {yy, mm, dd} is a valid date and initialize    Date(int yy, Month mm, char dd);    // ...private:    int y;    Month m;    char d;    // day};

译者注:这个例子的不变式是年月日的组合必须有效。

Note(注意)

If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.

如果一个类包含私有数据成员,使用者就不能在不使用构造函数的情况下完全初始化该类的对象。因此,类的定义者在提供构造函数的同时,必须定义其含义。这实际上意味着定义者需要定义不变式。


See also(参见):

  • define a class with private data as class

    使用class关键字定义包含私有数据的类。

  • Prefer to place the interface first in a class

    推荐在类的最初定义接口

  • minimize exposure of members

    最小限度暴露成员

  • Avoid protected data

    避免protected类型数据

Enforcement(实施建议)

Look for structs with all data private and classes with public members.

找到所有数据都被定义为私有的结构体和包含公有成员(应为数据成员,译者注)的类。


译者注:所谓原则就是不需要深入思考就可以执行,而效果却会逐渐显现的那些良好实践。


英文原文地址:https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-struct


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

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

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




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


浏览 37
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

举报