C++重载提取运算符 - 错误无法访问类中声明的私有成员

Ama*_*ine 5 c++ operator-overloading private-members ostream

我正在做一些功课并收到最奇怪的错误.希望你能提供帮助.我收到此错误:

无法在课堂上访问私人会员

注意:我显然没有写完这个,但我试着去测试错误.非常感谢您的任何输入!

// 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;
} 
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 2

std::ostream是不可复制的。您需要传递一个引用,并返回一个引用:

friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);

....
std::ostream& operator<<(std::ostream& player,  const SoccerPlayer& aPlayer) { /* as before */ }
Run Code Online (Sandbox Code Playgroud)

另请注意,没有理由不传递SoccerPlayer作为const参考。

在与错误完全无关的注释中,您应该更喜欢使用构造函数初始化列表,而不是为构造函数主体中的数据成员赋值:

SoccerPlayer::SoccerPlayer(int jersey, int goal, int assist) 
: jerseyNum(jersey), numGoal(goal), numAssists(assist) {}
Run Code Online (Sandbox Code Playgroud)