C++ 中的二元运算符重载

Binary Operator Overloading in C++

给出的问题: 使用友元函数获取私有变量,使用运算符重载计算球队每一方的总进球数。我是 C++ 的新手,无法弄清楚如何修复此错误。 我尝试过的:

Player operator-(Player &P1, Player &P2)
{
    Player P;
    P.goal=P1.goal+P2.goal;       
    return P;
}

错误:

main.cpp:104:17: error: no match for ‘operator-’ (operand types are ‘Player’ and ‘Player’)
    
main.cpp:26:8: note: candidate: Player operator-(Player&, Player&) 
 Player operator-(Player &P1, Player &P2)
        ^~~~~~~~
main.cpp:26:8: note:   conversion of argument 1 would be ill-formed:
main.cpp:104:14: error: invalid initialization of non-const reference of type ‘Player&’ from an rvalue of type ‘Player’
/usr/include/c++/6/bits/stl_iterator.h:1196:5: note: candidate: template decltype ((__x.base() - __y.base())) std::operator-(const std::move_iterator<_IteratorL>&, const std::move_iterator<_IteratorL>&)
     operator-(const move_iterator<_Iterator>& __x,
     ^~~~~~~~
/usr/include/c++/6/bits/stl_iterator.h:1196:5: note:   template argument deduction/substitution failed:
main.cpp:104:18: note:   ‘Player’ is not derived from ‘const std::move_iterator<_IteratorL>’
/usr/include/c++/6/bits/stl_iterator.h:1189:5: note: candidate: template decltype ((__x.base() - __y.base())) std::operator-(const std::move_iterator<_IteratorL>&, const std::move_iterator<_IteratorR>&)
     operator-(const move_iterator<_IteratorL>& __x,
     ^~~~~~~~
/usr/include/c++/6/bits/stl_iterator.h:1189:5: note:   template argument deduction/substitution failed:
main.cpp:104:18: note:   ‘Player’ is not derived from ‘const std::move_iterator<_IteratorL>’
/usr/include/c++/6/bits/stl_iterator.h:336:5: note:   template argument deduction/substitution failed:
main.cpp:105:18: note:   ‘Player’ is not derived from ‘const std::reverse_iterator<_Iterator>’
     

我是 C++ 的新手,无法理解这一点。

不通过 Player 作为运算符中的引用解决了问题:

Player operator-(Player P1, Player P2) {
    Player P;
    P.goal=P1.goal+P2.goal;       
    return P;
}

以及将它们作为对 const 的引用传递:

Player operator-(const Player &P1, const Player &P2) {
    Player P;
    P.goal=P1.goal+P2.goal;       
    return P;
}

我收到的错误消息非常有帮助:no match for ‘operator-’ (operand types are ‘Player’ and ‘Player’),而候选人是:‘Player operator-(Player&, Player&)’

现在我们都看到了。运算符returns按值(returns右值),而参数类型是非const左值引用,Player&.

然后 错误说明了一切

cannot bind non-const lvalue reference of type ‘Player&’ 
to an rvalue of type ‘Player’