构造函数中变量的 C++ 范围

c++ scope of variable in constructor

本文关键字:C++ 范围 变量 构造函数      更新时间:2023-10-16

我有 2 个类classNodeclassTree .在我的类树构造函数中,我创建了一个vector<classNode> nodes并推送返回classNodes对象。

然后我分配了一个classNode*指针指向 vector<classNode>

this->root= &nodes[0];

现在退出构造函数后,我的指针显示垃圾,但我必须使用它。我可以为此目的使用static vector<classNode> nodes吗?或者是有谁给我任何建议?

编辑

struct nodeInfo{
    string name;
    int tab;
};
ClassTree(){
    vector<nodeInfo> container;
         vector<ClassNode> nodes;
         //assume that container is a not-empty vector.I removed this part for simplicity.
         for(int i=0;i<container.size();i++){
          nodes.push_back(ClassNode (container[i].name,1));
    }
    this->root=&nodes[0];
}
ClassTree::function2(){
//now I want to use root here. I mean I want to reach &nodes[0] here.
}

如果我直接得到这个场景(显示代码会有很大帮助)。
您不应该在构造函数中创建vector<classNode> nodes,而应该将其作为 classTree 的成员。那也是root

==

编辑==

现在,在看到您的代码后,您应该将其更改为:

vector<ClassNode> nodes;移动到头文件中的类。

如果你不能更改标题(这是课堂作业吗?),你应该通过在nodeInfo结构中有一个leftright指针来改变你构建它的方式。 这样,拥有根将使您可以访问所有树曼伯。 此外,您必须使用new分配新节点,而不是在堆栈上设置参数并指向它们:

struct nodeInfo
{
    string name;
    int tab;
    nodeInfo *left;
    nofeInfo *right;
};
ClassTree(){
    vector<nodeInfo> container;
    vector<ClassNode> nodes;
    for(int i=0;i<container.size();i++)
    {
        nodeInfo newNode = new nodeInfo;// <-- use `new` so it will "live" out side the scope.
        newNode.name = ...;
        newNode.tab = ...;
        //here is the "magic" when you actually need to build the tree.
        //if it's the first one then root should point it.
        //otherwise it should be one of the root's childs
        //but you can't expect me to do everything for you (:
    }
    this->root=&nodes[0];
}
ClassTree::function2(){
//now I want to use root here. I mean I want to reach &nodes[0] here.
}

根据你的代码,你已将元素推送到构造函数的堆栈空间中的向量中。然后为元素 0 分配一个成员指针。一旦构造函数返回,指针就会变为无效。它在堆栈上 - 它不再是。