为什么“C ++核心指南”建议使用偏好的独立函数而不是类成员?

时间:2017-05-11 13:02:56

标签: c++ class-method

C++ Core Guidelines section C.4建议“只有在需要直接访问类的表示时才使函数成为成员”,使用以下示例:

class Date {
    // ... relatively small interface ...
};

// helper functions:
Date next_weekday(Date);
bool operator==(Date, Date);

我不明白这里的推理。在我看来,这将是一个更好的选择:

class Date {
    // ... relatively small interface ...

    Date next_weekday(Date const&) const;
    bool operator==(Date const&) const;
};

这种推理有什么好处?

2 个答案:

答案 0 :(得分:1)

会员功能可以访问班级的private个成员。这意味着他们可以在逻辑中使用类的内部表示。

非会员功能只能访问班级的public成员。这意味着它们只能使用类的公开接口,从而改善封装。

答案 1 :(得分:0)

增加封装

当您更改日期的私人实施时,您只需检查// ... relatively small interface ...以查找之前假设可能不再适用的地方,而不是// ... relatively small interface ... + next_weekday + {{1} } + ...