为什么"C++ Core Guidelines"推荐首选独立函数而不是类成员?

Why does the "C++ Core Guidelines" recommends the prefer independent functions instead of class members?

本文关键字:函数 成员 独立 Core C++ Guidelines 为什么      更新时间:2023-10-16

C++核心准则第 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;
};

这种推理的优势是什么?

成员函数可以访问类的private成员。这意味着他们可以在逻辑中使用类的内部表示形式。

非成员函数只能访问类的public成员。这意味着它们只能使用类的公开接口,从而改进了封装。

它增加了封装

当您更改 Date 的私有实现时,您只需检查// ... relatively small interface ...以前的假设可能不再成立的地方,而不是// ... relatively small interface ...+next_weekday+operator==+ ...