选择何时使用朋友功能

时间:2012-11-29 02:06:26

标签: c++ friend

参考C++ FAQ lite

它表示二进制中缀算术运算符:

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

有人可以解释为什么会这样吗?为什么对第一个参数的类型有约束?

谢谢。

2 个答案:

答案 0 :(得分:7)

考虑一下:

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!

答案 1 :(得分:3)

假设您有Foo类型,那么对于Foo f; int n;f + nn + f这两个表达式都有意义。

通过重载成员operator+,您只能实施f + n

struct Foo
{
    Bar operator+(int n) const;       // binds to "Foo + int"
    // ...
};

您永远无法从成员运营商那里获得其他版本int + Foo。解决方案是定义 free 运算符,该运算符可以用于涉及至少一个用户定义类型的任何签名。事实上,我们可以像这样回收成员运营商:

Bar operator+(int n, Foo const & f)   // binds to "int + Foo"
{
    return f + n;                     // recycle existing implementation
}

如果有一个空闲的运算符重载,那么将friend作为Foo通常是有意义的,这样它就可以访问该类的内部。在我们的例子中,我们并不需要这个,因为我们只是将调用传递给成员运算符。