如何将对象添加到另一个类中的向量<object>?</object>

时间:2010-11-15 10:04:12

标签: c++ class vector

#include "player.h"

class team
{
public:
 team();
 void addPlayer(player);
 void deletePlayer(int);
 double getTotalCost();
 int getPlayerCount();
 double inBank();
 string toString();

private:
 player a;
 int playerId;
 double bank;
 int i;
};


#include "../../std_lib_facilities.h"
#include "team.h"


team::team()
{
 vector <player> a;
 player a;
}

team::addPlayer(player)
{
 a.push_back(a);
}

如果需要更多信息,请询问。提前感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

我认为这就是你的意思:

#include "player.h"
#include  <vector>

class team
{
public:
 team();
 void addPlayer(player);
 void deletePlayer(int);
 double getTotalCost();
 int getPlayerCount();
 double inBank();
 string toString();

private:
 vector<player> a;
 int playerId;
 double bank;
 int i;
};

#include "../../std_lib_facilities.h"
#include "team.h"


team::team()
{
}

team::addPlayer(player p)
{
 a.push_back(p);
}

答案 1 :(得分:0)

你应该把你的vector变量作为你的类的一个成员,或者在堆上创建它,并保持指向它的指针。现在,您将在teem构造函数中的堆栈上创建向量。它将在构造函数完成时删除。  此外,您不能为播放器和矢量使用名称a。我建议你先阅读一些C ++书籍。

答案 2 :(得分:0)

这有很多错误,我不知道从哪里开始,你宣布一个单一的玩家,在这里:

private:
    player a; // why not just call every variable in your program "a"?

然后在团队的构造函数中:

team::team()
{
    vector<player> a;  // a vector that will be destroyed on exit from constructor
    player a; // another single player, but you've just defined 'a' so you should get a compiler error along the lines of redefinition.
}

我怀疑你想要这样的东西:

#include <vector>
#include <string>

#include "player.h"

class team
{
private:
    std::vector<player> m_Players;   // players

public:
    void addPlayer(const player& _player) { m_Players.push_back(_player); }
}; // eo class team

答案 3 :(得分:0)

你需要什么?将球员存放在你的班级团队中?

#include <iostream>
#include <vector>
using namespace std;

class Player
{
public:
    Player(int id)  {   m_id = id; }
    int GetId() {return m_id;   }
private:
    int m_id;
};

class team
{
public:
    team(){};
    void AddPlayer(Player p) {m_arr.push_back(p);}
    size_t Size(){  return m_arr.size();}
    Player GetPlayer(size_t index) {return m_arr[index];}
private:
    vector<Player> m_arr;
};

void main()
{
    team t;
    for (int i =0; i < 10; ++i)
    {
        t.AddPlayer(Player(i));
    }

    for (int i =0; i < t.Size();++i)
    {
        cout << "Player [" << i + 1 <<  "] with id: " << t.GetPlayer(i).GetId() << endl;
    }
}