gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:07 31 4
gpt4 key购买 nike

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

Cannot access private member in class

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

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

最佳答案

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

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

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

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

关于C++ 重载提取运算符 - 错误无法访问类中声明的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772825/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com