我正在做一些功课并收到最奇怪的错误。希望你能提供帮助。我收到了这个错误:
无法访问班级中的私人会员
注意:我显然没有写完这个,但我试着去测试错误。非常感谢您提供的任何意见!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
class SoccerPlayer
{
friend std::ostream operator<<(std::ostream, SoccerPlayer&);
// friend std::istream operator>>(std::istream, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
};
SoccerPlayer::SoccerPlayer(int jersey, int goal, int assist)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
std::ostream operator<<(std::ostream player, SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player ;
};
int main()
{
return 0;
}
答案 0 :(得分:3)
您希望通过引用传递和返回流:您无法复制IOStream对象。此外,在写入的情况下,您可能想要传递SoccerPlayer const&
。通过这些更改,您的代码应该是编译器(尽管在定义输出运算符之后还有一个多余的分号)。
也就是说,输出运算符应声明为
std::ostream& operator<< (std::ostream&, SockerPlayer const&)
(在其定义和friend
声明中)。
答案 1 :(得分:2)
std::ostream
不可复制。您需要传递引用,并返回引用:
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
....
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer) { /* as before */ }
另请注意,没有理由不将SoccerPlayer
作为const
引用传递。
在与错误完全无关的注释上,您应该更喜欢使用构造函数初始化列表,而不是将值赋给构造函数体中的数据成员:
SoccerPlayer::SoccerPlayer(int jersey, int goal, int assist)
: jerseyNum(jersey), numGoal(goal), numAssists(assist) {}
答案 2 :(得分:2)
您应该将ostream对象的引用发送给您的朋友函数。
所以它会像friend std::ostream& operator<<(std::ostream &, SoccerPlayer&);
无论是原型还是定义。
答案 3 :(得分:0)
std::ostream operator<<(std::ostream player, SoccerPlayer& aPlayer)
必须是班级的朋友或班级成员才能访问private
和protected
字段。