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

Posted

技术标签:

【中文标题】如何在对象数组中打印对象的变量【英文标题】:How to print a variable of an object inside an array of objects 【发布时间】:2018-04-26 10:40:42 【问题描述】:
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 

所以基本上我想在作为 Team 类的实例变量的对象数组中打印球员的姓名(这些是 Player 类的对象)。(第一次在这里提问请不要太苛刻” )

【问题讨论】:

Team::AddPlayers(p); // this function works 我对此表示怀疑。方法不是静态的,您可能应该使用Team team; team.AddPlayer(p); 你的播放器等级怎么样? 【参考方案1】:

您应该在您的 Player 类中覆盖 &lt;&lt;

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++ 中打印动态数组我需要解释这个问题

Firebase 引用对象不会保存到 SwiftUI 中的变量

如何从两个不同的数组中找到共同的对象并打印另一个对象?

打印对象数组的每个元素时出现问题[关闭]

如何打印 SimpleXMLElement 对象的特定数组元素

如何从jquery中的给定对象数组中打印用户名[重复]