gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:02:08 25 4
gpt4 key购买 nike

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 类的一个实例变量。(第一次在这里提问请不要太苛刻” )

最佳答案

你应该覆盖 <<在你的 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

但是在你的上下文中你需要重写你的 void 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();
//...

关于c++ - 如何在对象数组中打印对象的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50040906/

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