如何将新对象添加到 C++ 中的对象数组?

How to add new object to the array of objects in C++?

我有两个 class,即 Players Team Team class 中,我有 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 class 中实现 addNewPlayer 方法。 每当我调用这个方法时,我应该能够将玩家的名字添加到这个 Players 实例数组的末尾,即 players。现在我考虑的功能是:

void Team :: addNewPlayer(Players new_player){
       // add new_player to the end of the array
       }

我也知道 StacksQueues 数据结构。但是,仅使用数组有限制。
一般来说,有没有什么有效的方法可以将新对象添加到其他 class 中的对象数组中?

您需要了解您团队中的当前球员人数。然后,您需要将 new_player 添加到 players[currentcount]

players arrayTeam class 中定义.给它分配一个 size;您使用变量 MAXif 此变量使用适当的 value,假设一个不同于其最大容量的值取决于 hardware,您可以尝试创建一个新数组,用新的长度和元素替换 class 中的一个:

void Team::addNewPlayer(Players new_player) {

    // add new_player to the end of the array
    int newSize = sizeof(players)/sizeof(players[0]);
    Players newArray[newSize+1];
    
    for (int i=0; i < newSize; i++) {
        newArray[i] = players[i];
    }

    newArray[newSize] = new_player;
    players = newArray;
}