为什么"C++ Core Guidelines"推荐首选独立函数而不是类成员?
Why does the "C++ Core Guidelines" recommends the prefer independent functions instead of class members?
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==
+ ...
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针