选择何时使用好友功能

Choosing when to use a friend function

本文关键字:功能 好友 何时使 选择      更新时间:2023-10-16

请参阅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 + nn + 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
}

当您只有一个空闲运算符重载时,通常将其设置为Foofriend,以便它可以访问该类的内部。在我们的例子中,我们不需要这个,因为我们只是将调用传递给成员操作员。