【发布时间】: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 << p.goal;,因为goal没有被初始化。