【发布时间】:2021-12-29 16:43:42
【问题描述】:
我有两个类,即Players 和Team 在Team 类中,我有Players 实例数组和MAX_SİZE = 11
#define MAX 11
class Players{
// Some private and public members
};
class Team {
private:
Players players[MAX];
// Some other private and public members
};
我想在我的 Team 类中实现 addNewPlayer 方法。
每当我调用此方法时,我应该能够将播放器的名称添加到此Players 实例数组的末尾,即players。现在我考虑的功能是:
void Team :: addNewPlayer(Players new_player){
// add new_player to the end of the array
}
我也知道Stacks 和Queues 数据结构。但是,仅使用数组是有限制的。
一般来说,有没有什么有效的方法可以将新对象添加到其他类的对象数组中?
【问题讨论】:
-
players[currentNumberOfPlayers] = new_player? -
Players players[MAX];你不能改变它的大小——它固定在MAX。 -
在 C++ 中,数组没有“添加到末尾”的概念。如果一个数组包含 11 个玩家,则该大小无法更改。它永远只能容纳 11 名玩家。
-
@Johnny Mopp。是的,大小固定为 11,这是一个上限。我最多可以为球队增加 11 名球员。如果团队最初是空的,这有什么问题?
-
不要。将数组替换为
std::vector并使用std::vector::push_back()。