这里有一系列Agent,我想初始化一个Players数组。代理人只有他的名字。用户必须输入球员姓名,球衣号码和球员代理人。在这种情况下,我希望多个玩家能够拥有相同的代理,所以我使用了一个指针。
// Default constructor = Agent(std::string = "")
Agent agents[2] = {"Larry", "Joe"};
// Default constructor = Player(std::string = "", int = 0, Agent* = 0)
Player players[3];
initializePlayers(players, 3);
void initializePlayers(Player players[], int playerSize)
{
string playerName, agentName;
int playerNum;
Agent *myAgent;
for(int i = 0; i < playerSize; i++)
{
cout << "Please enter the player's name: ";
getline(cin, playerName);
cout << "Please enter the player's number: ";
cin >> playerNum;
cout << "Please enter the player's agent: ";
getline(cin, agentName);
cin.ignore(1000, '\n');
// If the agent's name matches one of the names in agents array
// assign that agent to this player
Player tempPlayer(playerName, playerNum, myAgent);
players[i] = tempPlayer;
}
}
在我的评论中,我需要分配myAgent。例如,如果用户为第一个玩家输入“Larry”,Larry应该是他的代理人。如果用户为接下来的两个玩家输入“Joe”,他们都应该将Joe作为他们的代理人。我该如何做到这一点?让我入门的想法也会有所帮助。谢谢。
答案 0 :(得分:0)
首先,您应该更好地使用std::array
之类的内容:
// Default constructor = Agent(std::string = "")
std::array<Agent, 2> agents = { Agent("Larry"), Agent("Joe") };
然后你可以搜索这样的代理:
myAgent = nullptr;
for (unsigned i = 0; i < agents.size(); ++i)
{
if (agentName == agents.getName())
myAgent = &agents[i];
}