问题描述
在他的书Effective C ++中提到的,在某些情况下,非成员非朋友功能的封装比成员函数更好。示例:
// Web浏览器允许清除
类WebBrowser {
public:
...
void clearCache();
void clearHistory();
void removeCookies();
...
};
许多用户都希望一起执行所有这些操作,所以 WebBrowser
也可以提供一个功能:
class WebBrowser {
public:
...
void clearEverything(); //调用clearCache,clearHistory,removeCookies
...
};
另一种方法是定义非会员非朋友功能。
void clearBrowser(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}
非成员函数更好,因为它不增加数字的功能,可以访问类的私人部分,从而导致更好的封装。
像 clearBrowser
是便利功能,因为它们不能提供任何功能, WebBrowser
客户端无法以其他方式获得。例如,如果 clearBrowser
不存在,客户端可以调用 clearCache
, clearHistory
和 removeCookies
自己。
对我来说,方便功能的例子是合理的。但是,当非会员版本擅长时,除了方便功能之外还有其他的例子吗?
更一般来说,什么时候使用哪个的规则是什么?
这是Scott Meyer的规则():
这几乎总结了一切,这在我看来也是很合理的。 / p>
Meyers mentioned in his book Effective C++ that in certain scenarios non-member non-friend functions are better encapsulated than member functions.
Example:
// Web browser allows to clear something
class WebBrowser {
public:
...
void clearCache();
void clearHistory();
void removeCookies();
...
};
Many users will want to perform all these actions together, so WebBrowser
might also offer a function to do just that:
class WebBrowser {
public:
...
void clearEverything(); // calls clearCache, clearHistory, removeCookies
...
};
The other way is to define a non-member non-friend function.
void clearBrowser(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}
The non-member function is better because "it doesn't increase the number of functions that can access the private parts of the class.", thus leading to better encapsulation.
Functions like clearBrowser
are convenience functions because they can't offer any functionality a WebBrowser
client couldn't already get in some other way. For example, if clearBrowser
didn't exist, clients could just call clearCache
, clearHistory
, and removeCookies
themselves.
To me, the example of convenience functions is reasonable. But is there any example other than convenience function when non-member version excels?
More generally, what are the rules of when to use which?
Here is what Scott Meyer's rules are (source):
Which pretty much sums it all up, and it is quite reasonable as well, in my opinion.
这篇关于我什么时候应该更喜欢非会员非朋友功能的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!