[英]Attempting to create a pointer to previous object inside object
I'm attempting to create a vector of pointers to Nodes, where each node stores a pointer to the previous Node in the list. 我试图创建一个指向节点的指针的向量,其中每个节点在列表中存储指向前一个节点的指针。
I made a small test program to see if I could access a variable gscore in the previous object to the one I call. 我编写了一个小型测试程序,以查看是否可以在上一个对象中访问我所调用的对象中的变量gscore。
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
Node(int gscore1)
{
gscore = gscore1;
}
Node *previous;
int gscore;
};
int main()
{
std::vector<Node*> nodeVec;
Node *tempnode;
tempnode = new Node(10);
Node *tempnode2;
tempnode = new Node(11);
nodeVec.push_back(tempnode);
nodeVec.push_back(tempnode2);
nodeVec[1]->previous = tempnode;
cout << nodeVec[1]->previous->gscore << endl;
return 0;
}
However this results in a crash. 但是,这会导致崩溃。 What is the correct way to do this?
正确的方法是什么?
You never initialize tempnode2. 您永远不会初始化tempnode2。 You initialize tempnode twice.
您初始化tempnode两次。
int main()
{
std::vector<Node*> nodeVec;
Node *tempnode;
tempnode = new Node(10);
Node *tempnode2;
tempnode2 = new Node(11); // <<---- HERE
nodeVec.push_back(tempnode);
nodeVec.push_back(tempnode2);
nodeVec[1]->previous = tempnode;
cout << nodeVec[1]->previous->gscore << endl;
return 0;
}
Looks like a typing error. 看起来像是打字错误。 The third line in main() should be tempnode2 not tempnode.
main()中的第三行应该是tempnode2而不是tempnode。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.