1
class Team
{
    string Color;
    int NumberOfPlayers;
public:
    Team();
    Team(string a);
    ~Team();

    Player TeamsPlayers[11];
    int Wins;

    //Getters| Setters
    void setColor(string Color);
    void setWins(int Wins);
    string getColor();
    int getNumberOfPlayers();
    int getWins();

    void status(Team ob); 
    void AddPlayers(Team ob);
};

void Team::status(Team ob)
{
    for(int i=0; i<counter; ++i)
    cout<< (ob.TeamsPlayers[i]).getName() <<endl;
}

int main()
{
    Player p;
    Team::AddPlayers(p); // this function works 
}

So basically I want to print the name of the players(these are objects from class Player) within the array of objects which is an instance variable of the class Team.(First time asking a question here please dont be too harsh")

1
  • 4
    Team::AddPlayers(p); // this function works I doubt it. method is not static, you should probably have Team team; team.AddPlayer(p); instead. Commented Apr 26, 2018 at 10:43

1 Answer 1

1

You should override << in your Player class:

class Player
{
    std::string Name;

public:
    Player(const char* name): Name(name)
    {
    }

    friend ostream& operator<<(ostream& os, const Player& dt);
};

ostream& operator<<(ostream& out_s, const Player& pl)
{
    out_s << "name is " << pl.Name << std::endl;
    return out_s;
}

For example you can print your players now like this:

int main()
{
    // Init with a help of non-explicit constructor
    Player TeamsPlayers[11] = {"GK","LD","CD","CD","RD","LM","CM","CM","RM","LF","RF"};
    //Print players 
    std::copy(TeamsPlayers, TeamsPlayers+11, std::ostream_iterator<Player>(std::cout));

}

And output is:

name is GK
name is LD
name is CD
name is CD
name is RD
name is LM
name is CM
name is CM
name is RM
name is LF
name is RF

But in case of your context you need to rewrite your void Team::status:

void Team::status(Team ob)
{
    int Length = ob.getNumberOfPlayers();
    for(int i=0; i<Length; ++i)
    cout<< ob.TeamsPlayers[i] <<endl;
}

Also you don't have to pass Team ob as parameter if you want to access its own members of object. You can rewrite method as:

void Team::status()
{
    int Length = getNumberOfPlayers();
    for(int i=0; i<Length; ++i)
    cout<< TeamsPlayers[i] <<endl;
}

And the just call it as:

//...
Team liverpoolTeam;
liverpoolTeam.status();
//...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.