5

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

无法访问班级中的私人成员

注意:我显然还没有写完,但我会尝试测试错误。非常感谢您的任何意见!

// 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;
} 
4

4 回答 4

3

您想通过引用传递和返回流:您不能复制 IOStream 对象。此外,在写入的情况下,您可能想要传递一个SoccerPlayer const&. 通过这些更改,您的代码应该编译(尽管在输出运算符的定义之后还有一个多余的分号)。

也就是说,您的输出运算符应声明为

std::ostream& operator<< (std::ostream&, SockerPlayer const&)

(在其定义和friend声明中)。

于 2012-10-07T21:06:46.947 回答
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) {}
于 2012-10-07T21:07:18.133 回答
2

您应该将 ostream 对象的引用发送给您的朋友函数。所以它friend std::ostream& operator<<(std::ostream &, SoccerPlayer&); 在原型和定义上都类似。

于 2012-10-07T21:08:19.143 回答
0

std::ostream operator<<(std::ostream player, SoccerPlayer& aPlayer)必须是班级的朋友或班级成员才能访问privateprotected字段。

于 2012-10-07T21:06:48.883 回答