我有兩個類,即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
};
我想addNewPlayer在我的Team 班級中實作該方法。每當我呼叫此方法時,我應該能夠將播放器的名稱添加到此Players實體陣列的末尾,即players. 現在我考慮的功能是:
void Team :: addNewPlayer(Players new_player){
// add new_player to the end of the array
}
我也知道Stacks和Queues資料結構。但是,僅使用陣列是有限制的。
一般有沒有什么有效的方法可以將新物件添加到其他類中的物件陣列中?
uj5u.com熱心網友回復:
players 陣列在Team 類中定義。給它分配一個大小;你使用變數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;
}
uj5u.com熱心網友回復:
您將需要團隊中當前的玩家人數。然后你需要添加一個 new_player 到玩家 [currentcount]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360350.html
上一篇:C 確保物件在執行函式時存在
下一篇:如何找到最接近整數的回文?
