构造函数中变量的 C++ 范围
c++ scope of variable in constructor
我有 2 个类classNode
和 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.
}
如果我直接得到这个场景(显示代码会有很大帮助)。
您不应该在构造函数中创建vector<classNode> nodes
,而应该将其作为 classTree
的成员。那也是root
。
编辑==
现在,在看到您的代码后,您应该将其更改为:
应vector<ClassNode> nodes;
移动到头文件中的类。
如果你不能更改标题(这是课堂作业吗?),你应该通过在nodeInfo
结构中有一个left
和right
指针来改变你构建它的方式。 这样,拥有根将使您可以访问所有树曼伯。 此外,您必须使用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 分配一个成员指针。一旦构造函数返回,指针就会变为无效。它在堆栈上 - 它不再是。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围