简体   繁体   中英

How to group objects of one class as an array of objects in another class?

I've made a class called Player , whose goal is to create a new object player that has these attributes as below and vector of 5 strings (skills of player).

Player(string name, string surname, int height, vector<string> skills) {
    this->name = name;
    this->surname = surname;
    this->height = height;
    this->skills = skills;
}

I've also created a method that shows data of an object.

// Method showing data
string show_data() {
    stringstream ss;
    string s;

    ss <<
        this->name << " " <<
        this->surname << " " <<
        this->height << " ";
    for (int i = 0; i < 5; i++) {
        ss << this->skills[i] << " ";
    }
    ss << "\n";
    s = ss.str();
    return s;
}

My goal is to group 5 players into one team in another class. I've printed out the data of players

cout << "Liverpool\n" << p1.show_data() << p2.show_data() << p3.show_data() << p4.show_data() << p5.show_data() << endl

But I want to have something like cout << liverpool.show_data(); and it should print the data of all 5 players

cout << real_madrit.show_data(); etc..

The question arises, how can I pass these 5 objects to another class with their attributes?

You can just create a new class that has Players.

class Team
{
private:

  std::vector<Player> players_;

public:

  Team(std::vector<Player> p) : players_(p) {}

  void show_data() const
  {
    for (auto const & player : players_)
      std::cout << player.show_data();
  } 
};

Now you can use this class like so.

std::vector<Player> p = /* create a bunch of players */
Team team(p); // create a Team
team.show_data(); // display the team

If you try to compile this example, you will get an error, because each player in the for loop in Team::show_data() is marked as a const-reference. You could remove the const here, but don't do that. (After all, showing the data of a Team/Player shouldn't modify the Team/Player). So instead, make your Player::show_data() a const method.

Note that this will allow teams of any number of players. If you definitely want just 5 per team, then your players_ member could be an array

std::array<Player, 5> players_;

If you see the Team class constructor, you might see the initializer list syntax. You could use that for your Player constructor as well, and it becomes

Player(string name, string surname, int height, vector<string> skills) 
 : name(name), surname(surname), height(height), skills(skills) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM