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

58a1b3c95a9bb9f04c252b2e5df3507d.png

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.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值