如何在对象数组中打印对象的变量

时间:2018-04-26 10:40:42

标签: c++ arrays class

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 
}

所以基本上我想在对象数组中打印玩家的名字(这些是来自Player类的对象),这是Team类的实例变量。(第一次在这里问一个问题请不要太苛刻“ )

1 个答案:

答案 0 :(得分:1)

您应该在Player类中覆盖<<

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

例如,您可以像这样打印您的玩家:

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));

}

输出是:

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

但是如果您的上下文需要重写您的空Team::status

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

如果您想访问自己的对象成员,也不必将Team ob作为参数传递。您可以将方法重写为:

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

然后将其称为:

//...
Team liverpoolTeam;
liverpoolTeam.status();
//...