【问题标题】:Binary Operator Overloading in C++C++ 中的二元运算符重载
【发布时间】:2021-06-12 10:02:14
【问题描述】:

给定的问题: 使用友元函数获取私有变量和运算符重载来计算团队每一方的目标总数。我对 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 p; std::cout &lt;&lt; p.goal;,因为goal 没有被初始化。

标签: c++ operator-overloading


【解决方案1】:

在运算符中不传递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&amp;, Player&amp;)’

现在我们看到了这一切。运算符按值返回(返回右值),而参数类型是非const 左值引用,Player&amp;

然后错误说明了一切

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

【讨论】:

  • @EurekaChan 不客气!顺便说一句,欢迎来到 SO!如果您认为某个答案是已接受的,请不要忘记将答案标记为已接受。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 2011-10-06
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多