我正在学习类/继承/指针如何在 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;
};
当我创建一个新实例以传递给 void 函数(分别如下)时,尚未分配内存。
实例
unit **units = 0;
虚函数原型
void initialize(grid *grids, unit **units /*, plant **plants, predator **predators */);
使用一些参数在 void 函数中分配内存:
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
}
}
但是,一旦我退出 void 函数,我刚刚存储的数据就会被删除。指针声明和传递到函数中是否有问题(如下)?
initialize(&environment, units, plants, predators);
注意:我只有在unit类下声明的units变量有问题。环境变量没问题。其他两个(植物和捕食者)类似于units,所以如果修复了,我可以修复其他的。
第二注:主要功能如下(相关部分):
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;
}
感谢您提供的任何帮助/链接/解释。