c++ - 指向 void 函数中的类的指针

标签 c++ class pointers inheritance

我正在学习类/继承/指针在 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;

无效函数原型(prototype)

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 变量有问题。 环境 变量没问题。其他两个(植物捕食者)与单位 类似,所以如果这个修复了,我可以修复其他的。

第二个注意事项:主要功能如下(相关部分):

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

感谢您提供的任何帮助/链接/解释。

最佳答案

您将 units 按值 传递给函数。这意味着函数中的 units 指针开始时是调用代码中指针的拷贝。在函数中,您为本地 units 变量分配一个新值(即一些新创建对象的地址)。然后当函数终止时,局部变量超出范围并且它指向的对象丢失。调用代码中的指针永远不会被修改,并且对此一无所知。

改为通过引用传递:

void initialize(grid *grids, unit ** &units)

关于c++ - 指向 void 函数中的类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17757928/

相关文章:

c++ - 使用 C++ 时出现错误 : no matching function for call to ,

java - 如何从不同的类访问变量

c - 为什么在同一地址空间的两个不同指针上调用 malloc?

c - 将数组作为函数参数传递并设置元素值

c++ #define 并连接大小写(我使用的是 gcc)

c++ - 如何在 win 2003 上使用 VC6 附加到进程?

c++ - 如何修复只读对象中成员的错误分配?

android - 从静态 fragment 类调用主类中的方法

c++ - 在 PDF 页面上渲染图像

c++ - 为什么对于每个数组 a 和整数 j,a[j] 都等于 j[a]?