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関数に送信する必要があります。friend std::ostream& operator<<(std::ostream &, SoccerPlayer&); したがって、プロトタイプと定義の両方のようなものになります。

于 2012-10-07T21:08:19.143 に答える
0

std::ostream operator<<(std::ostream player, SoccerPlayer& aPlayer)privateおよびフィールドにアクセスするには、クラスの友達またはクラスメンバーである必要がありprotectedます。

于 2012-10-07T21:06:48.883 に答える