【问题标题】:How to add new object to the array of objects in C++?如何将新对象添加到 C++ 中的对象数组中?
【发布时间】: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
       }

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

【问题讨论】:

  • players[currentNumberOfPlayers] = new_player?
  • Players players[MAX]; 你不能改变它的大小——它固定在MAX
  • 在 C++ 中,数组没有“添加到末尾”的概念。如果一个数组包含 11 个玩家,则该大小无法更改。它永远只能容纳 11 名玩家。
  • @Johnny Mopp。是的,大小固定为 11,这是一个上限。我最多可以为球队增加 11 名球员。如果团队最初是空的,这有什么问题?
  • 不要。将数组替换为std::vector 并使用std::vector::push_back()

标签: c++ class object oop


【解决方案1】:

 players arrayTeam class 中定义。给它分配一个大小;你使用变量MAX如果这个变量使用一个合适的,假设一个不同于它的最大容量,这取决于硬件,您可以尝试创建一个新数组,用新的长度和元素替换其中的一个:

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;
}

【讨论】:

    【解决方案2】:

    您需要团队中当前的玩家人数。然后你要添加一个 new_player 到 player[currentcount]

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2012-11-16
    • 2020-09-01
    • 2022-01-16
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多