【发布时间】:2013-07-19 10:30:41
【问题描述】:
我正在学习类/继承/指针如何在 C++ 中工作并编写以下代码。
我有一个类 unit 声明如下:
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 变量有问题。 environment 变量很好。另外两个(plants和predators)和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;
}
感谢您提供的任何帮助/链接/说明。
【问题讨论】:
-
@Beta:感谢您的修复。现在可以使用了!
标签: c++ class pointers inheritance