我正在尝试用 C++ 制作一个简单的多人游戏,它需要能够拥有可变数量的玩家。我想我可以通过为每个玩家创建一个具有“分数”值的类来处理这个问题,然后每个玩家将成为该类的一个单独成员。
int main(void)
{
int input_players;
cout << "Welcome to Pig" << endl;
cout << "Please enter the number of players: ";
cin >> input_players;
int *playersarray = new int[input_players];
for (int i = 1; i <= input_players; ++i)
{
playersarray[i] = i;
//scores playersarray[i];
cout << playersarray[i] << endl;
}
system("PAUSE");
}
class scores
{
public:
int last_roll;
int turn_total;
int total_score;
};
在 for 循环中,您可以看到我的问题,我试图通过创建该行已被注释掉的类的不同成员来创建玩家数量。因为我不知道每次会有多少玩家上场,所以我不能宣布成员是正常的。例如:
scores player1
scores player2
scores player3
无论如何我可以根据用户输入的数字创建成员数量吗?
最佳答案
您可以使用 std::vector
和所有玩家的 push_back
得分实例来代替内置数组,然后您可以通过索引访问这些实例。或者,如果您想按玩家姓名访问分数,您也可以使用 std::map
/std::unordered_map
。这些数据结构也为您处理内存管理。
关于C++:如何根据用户的输入创建一个类的多个成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129832/