我应该何时更喜欢非会员非朋友功能到会员功能?

Eri*_*c Z 17 c++ encapsulation

Meyers在他的书"Effective C++"中提到,在某些情况下,非成员非朋友函数比成员函数更好地封装.

例:

// Web browser allows to clear something
class WebBrowser {
public:
  ...
  void clearCache();
  void clearHistory();
  void removeCookies();
  ...
};
Run Code Online (Sandbox Code Playgroud)

许多用户希望一起执行所有这些操作,因此WebBrowser也可能提供一个功能:

class WebBrowser {
public:
  ...
  void clearEverything();  // calls clearCache, clearHistory, removeCookies
  ...
};
Run Code Online (Sandbox Code Playgroud)

另一种方法是定义非成员非朋友函数.

void clearBrowser(WebBrowser& wb)
{
  wb.clearCache();
  wb.clearHistory();
  wb.removeCookies();
}
Run Code Online (Sandbox Code Playgroud)

非成员函数更好,因为"它不会增加可以访问类的私有部分的函数的数量.",从而导致更好的封装.

喜欢的功能clearBrowser方便的功能,因为他们不能提供任何功能的WebBrowser一些其他方式的客户端无法获得已.例如,如果clearBrowser不存在,客户可以只打电话clearCache,clearHistoryremoveCookies他们自己.

对我而言,便利功能的例子是合理的.但是当非会员版本擅长时,除了便利功能之外还有其他例子吗?

更一般地说,什么时候使用哪些规则

Naw*_*waz 21

更一般地说,什么时候使用哪些规则?

以下是Scott Meyer的规则(来源):

Scott有一篇有趣的文章,主张非成员非朋友函数改进了类的封装.他使用以下算法来确定函数f的放置位置:

if (f needs to be virtual)
    make f a member function of C;
else if (f is operator>> or operator<<)
{
   make f a non-member function;
   if (f needs access to non-public members of C)
      make f a friend of C;
}
else if (f needs type conversions on its left-most argument)
{
   make f a non-member function;
   if (f needs access to non-public members of C)
      make f a friend of C;
}
else if (f can be implemented via C's public interface)
   make f a non-member function;
else
   make f a member function of C;
Run Code Online (Sandbox Code Playgroud)

他对封装的定义涉及私有数据成员更改时受影响的函数数量.

在我看来,这几乎总结了一切,这也很合理.