【问题标题】:c++ scope of variable in constructor构造函数中变量的c ++范围
【发布时间】:2013-12-29 09:58:42
【问题描述】:

我有 2 个班级 classNodeclassTree。 在我的 classTree 构造函数中,我创建了一个 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.
}

【问题讨论】:

  • 堆栈溢出经验法则 #3:“现在,众所周知”之后是一些完全的误解。
  • 可以显示classTree构造函数的代码吗?
  • @KerrekSB - 以及 which is obviously true..democratic republic of...
  • @EdHeal:我的最爱:“我的程序运行良好。只有一件事:”(UB 紧随其后)
  • @RoeeGavirel 我添加了它

标签: c++ pointers scope


【解决方案1】:

如果我能正确理解场景(显示代码会有很大帮助)。
您不应在构造函数中创建vector&lt;classNode&gt; nodes,而应将其作为classTree 的成员。 root 也是如此。

==编辑==

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

您应该将vector&lt;ClassNode&gt; nodes; 移动到头文件中的类。

如果您不能更改标题(这是一个班级作业吗?)您应该通过在nodeInfo 结构中使用leftright 指针来更改构建它的方式。这样就可以让您获得对所有 Tree 成员的访问权限。此外,您必须使用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.
}

【讨论】:

  • 感谢您的回复。我不更改标题,root 是 classTree 顺便说一句的成员。有没有其他办法?
【解决方案2】:

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

【讨论】:

  • 你真的应该描述你想做什么。为什么你的构造函数做它是什么?只有这样我们才能提供帮助。
  • 我需要在 classTree 的另一个方法中通过根指针到达 vector 节点。就是这样。 @Raja
  • 如果您想在构造函数中创建它,那么您需要将该向量 存储为成员变量。否则,您可以将其移至普通函数并从那里返回。
  • @caesar :我明白这一点。你的构造函数首先是如何得到这个向量的?你的代码显示你初始化它 - 如果是这样,你为什么不让它成为一个类成员?
  • 你需要将节点放在向量中吗?在我看来,您被要求进行显式的堆分配和释放。哪些现代 C++ 代码做的不多,但它仍然很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多