c++ - 非成员非友元函数真的增加了封装性吗?

标签 c++

我目前正在阅读 Scott Meyers 的 Effective C++ 一书,但我无法理解第 23 项。他说:

Prefer non-member non-friend functions to member functions. Doing so increases encapsulation, packaging flexibility, and functional extensibility.

虽然我可以看到在类外添加外部函数的意义,但我看不到它的优势。他谈到了这些,因为它们正在增加封装。嗯,是的,这是正确的,因为非成员非友元函数将无法访问在类中声明为私有(private)成员变量的任何成员变量。但是,这就是我无法解决的问题。拥有允许对象控制的成员函数在某种程度上是必不可少的——在所有数据成员都是公共(public)的 POD 中可以做什么?老实说,我在那里看不到任何实际用途。话虽如此,即使我们有非成员非友元函数,封装也不会改变,因为我们仍然需要 !!public!! MEMBER 函数与我们的对象进行交互。

那么为什么我 - 或其他任何人 - 更喜欢非成员非友元函数而不是成员函数?当然,我们可以在已经存在的成员函数上编写包装器,这可能会按逻辑顺序对它们进行分组,但仅此而已。我在这里看不到任何减少的封装。

最佳答案

Meyers 在 this article 中给出了他的推理.这是一个摘录:

We've now seen that a reasonable way to gauge the amount of encapsulation in a class is to count the number of functions that might be broken if the class's implementation changes. That being the case, it becomes clear that a class with n member functions is more encapsulated than a class with n+1 member functions. And that observation is what justifies my argument for preferring non-member non-friend functions to member functions: if a function f could be implemented as a member function or as a non-friend non-member function, making it a member would decrease encapsulation, while making it a non-member wouldn't.

关于c++ - 非成员非友元函数真的增加了封装性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26145639/

相关文章:

c++ - 如何使用 qtcreator 链接到 Arch Linux 上的 yaml-cpp?

c++ - '::' 标记之前的预期构造函数、析构函数或类型转换

c++ - 使用 shared_ptr 的找到/未找到指示

c++ - 嵌套模板特化

c++ - MSVC 2010 是符合 C++11 标准的编译器吗

使用 PCL 时私有(private)函数的 C++ 继承

c++ - FLENS 的自定义存储

c++ - 析构函数——我应该使用 delete 还是 delete[]?

c++ - 奇异迭代器的赋值

c++ - 什么时候应该对具有依赖空指针常量表达式参数的非限定函数调用进行名称查找?