选择何时使用好友功能
Choosing when to use a friend function
请参阅C++常见问题精简
版它指出二进制中缀算术运算符:
member functions don't allow promotion of the left hand argument, since that
would change the class of the object that is the recipient of the member
function invocation
有人可以解释为什么会这样吗?为什么对第一个参数的类型有限制?
谢谢。
考虑一下:
struct Number {
Number(int val) : val(val) { } // *Not* explicit
int val; // Everything public to simplify example
Number operator+(Number const& other) const { return val + other.val; }
};
Number n(42);
Number result = 32 + n; // Doesn't compile
但是,如果我们删除成员运算符并将其改为免费函数:
Number operator+(Number const& a, Number const& b) { return a.val + b.val; }
Number n(42);
Number result = 32 + n; // Compiles!
假设您有一个类型Foo
,以便对于Foo f; int n;
表达式f + n
和n + f
都有意义。
通过重载成员operator+
,你只能实现f + n
:
struct Foo
{
Bar operator+(int n) const; // binds to "Foo + int"
// ...
};
您永远无法从成员运算符int + Foo
获取其他版本。解决方案是定义自由运算符,可以为涉及至少一个用户定义类型的任何签名创建自由运算符。实际上,我们可以像这样回收成员运算符:
Bar operator+(int n, Foo const & f) // binds to "int + Foo"
{
return f + n; // recycle existing implementation
}
当您只有一个空闲运算符重载时,通常将其设置为Foo
的friend
,以便它可以访问该类的内部。在我们的例子中,我们不需要这个,因为我们只是将调用传递给成员操作员。
相关文章:
- 有没有可能有一个只有ADL才能找到的非好友功能
- 解析模板的好友功能时出现问题
- 特定好友功能专业化
- 好友功能 - 成员无法访问
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- 好友功能仍无法访问私人会员
- CUDA C++中的好友功能
- 我无法获得好友会员功能以实际访问私人会员
- 好友功能没有访问私人成员
- 我无法正确使用好友功能
- 如何更恰当地处理好友功能
- 为什么我的好友功能无法访问私人会员?
- 好友功能和受保护的数据
- 选择何时使用好友功能
- 好友功能"non-lvalue in assignment"
- 好友功能无法访问私人数据成员
- 在C++中使用好友功能有什么额外的优势?
- 成员无法使用好友功能访问
- 即使将会员功能设为好友也无法访问会员
- 好友功能 - 无法访问私人字段C++