Hello i need help, I do not understand why lines 31-35 are inaccessible? What am
ID: 3571896 • Letter: H
Question
Hello i need help, I do not understand why lines 31-35 are inaccessible? What am I doing wrong here?
// ConsoleApplication19.cpp : main project file.
#include "stdafx.h"
using namespace System;
#include<iostream>
#include<conio.h>
using namespace std;
class SoccerPlayer
{
private:
int jersyNumber;
int goals;
int assists;
public:
SoccerPlayer(int=0,int=0,int=0);
friend istream& operator>>(istream &in, const SoccerPlayer& player);
bool operator>(SoccerPlayer& job);
};
SoccerPlayer::SoccerPlayer(int jersyNumber, int goals, int assists)
{
this->jersyNumber=jersyNumber;
this->goals=goals;
this->assists=assists;
}
istream& operator>>(istream &in, SoccerPlayer& player)
//line 31-35 here
{
cout << "Enter jersy number: ";
in >> player.jersyNumber; //inaccessible?
cout << "Enter of goals: ";
in >> player.goals; //inaccessible?
cout << "Enter number of assists: ";
in >> player.assists; //inaccessible?
return in;
}
ostream& operator << (ostream &out, const SoccerPlayer& player)
{
out << "Jersy Number: " << "Goals: " << "Assists: " << endl;
return out;
}
bool SoccerPlayer::operator> (SoccerPlayer& otherPlayer)
{
return (goals+assists)>(otherPlayer.goals+otherPlayer.assists);
}
int main()
{
SoccerPlayer players[11]=
{
SoccerPlayer(100,10,10),
SoccerPlayer(101,11,11),
SoccerPlayer(102,12,12),
SoccerPlayer(103,13,13),
SoccerPlayer(104, 14,14),
SoccerPlayer(105,15,15),
SoccerPlayer(106,16,16),
SoccerPlayer(107,17,17),
SoccerPlayer(108,18,18),
SoccerPlayer(109,19,19),
SoccerPlayer(110,20,20)
};
SoccerPlayer maxPlayer;
for (int i=0; i<11; i++)
{
if (players[i]>maxPlayer)
{
maxPlayer=players[i];
}
}
cout << "Max Score player: " << maxPlayer << endl;
_getch();
return 0;
}
Explanation / Answer
The problem with your friend function istream>>() overloading is that, you declared the variable SoccerPlayer& player as const, which it is not supposed to be. istream will read a value into the player object, and if you declare it as constant means, you're not allowed to modify the object within the method.
So, the solution is, just remove the const keyword in the declaration, which will solve the problem. Hopefully, thats the only problem with your code.
So, the function declaration should be:
friend istream& operator>>(istream &in, SoccerPlayer& player);
and not friend istream& operator>>(istream &in, const SoccerPlayer& player);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.