gpt4 book ai didi

c++ - 什么时候我应该更喜欢非成员非 friend 函数而不是成员函数?

转载 作者:IT老高 更新时间:2023-10-28 22:12:33 31 4
gpt4 key购买 nike

Meyers 在他的《Effective C++》一书中提到,在某些场景下,非成员非友元函数比成员函数封装得更好。

例子:

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

许多用户都希望同时执行所有这些操作,因此 WebBrowser 也可能提供一个功能来做到这一点:

class WebBrowser {
public:
...
void clearEverything(); // calls clearCache, clearHistory, removeCookies
...
};

另一种方式是定义一个非成员非好友函数。

void clearBrowser(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}

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

clearBrowser 之类的函数是便利函数,因为它们不能提供 WebBrowser 客户端无法通过其他方式获得的任何功能.例如,如果 clearBrowser 不存在,客户端可以自己调用 clearCacheclearHistoryremoveCookies

对我来说,便利函数的例子是合理的。但是当非成员(member)版表现出色时,除了便利功能之外还有什么例子吗?

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

最佳答案

More generally, what are the rules of when to use which?

以下是 Scott Meyer 的规则 (source):

Scott has an interesting article in print which advocates that non-member non-friend functions improve encapsulation for classes. He uses the following algorithm to determine where a function f gets placed:

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;

His definition of encapsulation involves the number of functions which are impacted when private data members are changed.

在我看来,这几乎概括了一切,而且也很合理。

关于c++ - 什么时候我应该更喜欢非成员非 friend 函数而不是成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7821315/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com