我正在學習C++中的類/繼承/指針是如何工作的,並對以下代碼進行編碼。指向無效函數內的類
我有一個類單元聲明爲這樣:
class unit{
public:
int locationX,locationY;
//genotype (does not change)
float agility, build,size,stamina, aggression;
//phenotype (changes based on genotype and stimuli)
float speed, strength, hunger;
};
當我創建一個新的實例給進入的空隙功能(下面,分別地),所述存儲器還沒有分配。
實例
unit **units = 0;
void函數原型
void initialize(grid *grids, unit **units /*, plant **plants, predator **predators */);
存儲器被使用的一些參數的空隙函數內分配:
void initialize(grid *grids, unit **units,plant **plants,predator **predators)
{
units = new unit*[int(((grids->gridHeight)*(grids->gridWidth)*(grids->gridDivision))/20)];
for(register int i = 0; i<int(((grids->gridHeight)*(grids->gridWidth)*(grids->gridDivision))/20); i++)
{
units[i] = new unit;
units[i]->hunger = 5;
units[i]->locationX = (rand()%((grids->gridWidth)-0));
units[i]->locationY = (rand()%((grids->gridHeight)-0));
//etc, etc
}
}
然而,一旦I E xit void函數,我剛存儲的數據被刪除。指針聲明和傳入函數有什麼問題(如下所示)?
initialize(&environment, units, plants, predators);
注意:我只有用單位下單元類中聲明變量的問題。 環境變量很好。另外兩個(植物和掠食者)類似單位,所以如果這是固定的,我可以修復其他人。
其次注意:主要功能如下(相關部分):
int main()
{
unit **units = 0; //<--- Important one
plant **plants = 0;
predator **predators = 0;
grid environment(250,250,5); //Constructor for environment (don't mind this)
initialize(&environment, units, plants, predators); //<-- Void function
running = true;
return 0;
}
感謝您的幫助/鏈接/解釋,你可以提供。
@Beta:謝謝你的修復。它現在有效! – asuprem