此答案重点解决您的问题的第二部分,
引自 C++ 编码标准:101 条规则、指南和最佳实践:
第 44 章。更喜欢编写非成员非友元函数
[...] 非成员非友元函数通过最小化依赖关系来改进封装 [...]
Scott Meyers 提出了以下算法,用于确定哪些方法应该是类的成员(来源)
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;
至于你问题的前半部分,我猜编译器会优化任何差异。