如何访问超出范围的变量? [英] How to access a variable that is out of scope?

查看:43
本文介绍了如何访问超出范围的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class foo{
    vector<foo*>* queue;
    vector<int> pos;
    foo(vector<foo*>* queue, vector<int> pos){
        this->queue=queue;
        this->pos=pos;
    }
public:
    foo(vector<foo*>* queue){
        this->queue=queue;
    }
    void init(){
        vector<int> posNew = pos;
        //Create Binary Tree Children of the state FOO
        posNew.push_back(/* An Additional Value*/)
        foo newFoo(queue, posNew);
        queue->push_back(&newFoo);
    }//Here the variables newFoo and posNew are out of scope so they are deleted even from the queue
}

class bar{
    vector<foo*> queue; //Assume that queue has a root node added to it.
    bar(){
        for(unsigned int i=0; i<queue.size();i++){
            queue[i]->init();// Somewhere along when the third element is calculated the value overflows since I assume the object are deleted
        }
    }
}

我正在尝试使用带有队列的 BFS 搜索来解决问题.但是我无法让队列工作,因为我创建的对象子对象超出了范围.对此的任何帮助将不胜感激.

I am trying to use BFS search with a queue to solve a problem. However I am not able to get the queue to work since the object child object I create are going out of scope. Any help of this would be appreciated.

在我的实际代码中,我遇到了麻烦,因为当对象超出范围时,它会向我显示这些内存分配.

In my actual code, I am having trouble since when the object goes out of scope it shows me these memory allocations.

这个绿色部分是根节点所在的位置,红色部分是子节点的预期数据应该在的位置,但现在被删除了.

This green part is where the root node is, the red part is where the expected data for the child nodes was supposed to be but its now deleted.

推荐答案

变量 queuefoo 指针的向量,而不是 foo对象.但是在 init() 中,您将 newFoo 声明为 foo 对象并将其推送到队列中.newFoo是函数init()的局部变量,所以当函数执行完毕,newFoo丢失.

The variable queue is a vector of foo pointers, not foo objects. But in init(), you are declaring newFoo as a foo object and pushing it in the queue. newFoo is a local variable of function init(), so when the function finishes execution, newFoo is lost.

你可以将 newFoo 声明为一个指针并为其分配内存,比如

You can declare newFoo as a pointer and allocate memory for it, like

foo *newFoo = new foo(queue, posNew);

并将 newFoo 推送到您的队列中.

and push newFoo in your queue.

这篇关于如何访问超出范围的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆