#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Node{
private:
Node *parent;
string name;
public:
Node(){
}
Node(string nodeName, Node *nodeParent){
setName(nodeName);
setParent(nodeParent);
}
Node getParent(){
return *parent;
}
void setParent(Node *p){
parent = p;
}
string getName(){
return name;
}
void setName(string n){
name = n; //<--this is where the code fails...
}
};
class Child1 : public Node {
};
class Child2 : public Node {
};
class Graph {
private:
string name;
Node root;
void setName(string n){ name = n; }
void setRoot(Node r){ root = r; }
public:
Graph(string n, Node r){ //Constructor
setName(n);
setRoot(r);
Node *root = new Node();
string name = "Root";
root->setName(name);
Node *node1 = new Node("Node1", root);
Node *node2 = new Node("Node2", root);
Node *node3 = new Node("Node3", node2);
Child1 *child1;
child1->setName("Child1");
child1->setParent(root);
Child2 *child2;
child2->setName("Child2");
child2->setParent(node1);
}
string getName(){
return name;
}
Node getRoot(){
return root;
}
};
int main() {
Node *root = new Node();
root->setName("Root");
Graph *sg = new Graph("Graph", *root);
};
大家好。我正在嘗試構建一個節點結構。但是,如您所見,我并不擅長 C 。我在 Visual Studio Code 中遇到Segmentation fault (core dumped) 錯誤。所以也在https://pythontutor.com/ 中嘗試過,它給了我ERROR: Use of uninitialised value of size 8。我找不到在哪里初始化name。你能幫助我嗎?
而且代碼效率不高。我不得不定義兩個單獨的根:一個在 main() 中,一個在 Graph Constructor 中,因為無法弄清楚如何使用指標。如果您能解釋一種使其更有效的方法,那就太好了。但現在沒有那么必要。
編輯
我為 Child1 和 Child2 創建了結構。然后改成:Child1 *child1; to Child1 *child1 = new Child1(); 子2 *子2;到 Child2 *child2 = new Child2(); 錯誤消失了。
uj5u.com熱心網友回復:
Child1 *child1;
child1->setName("Child1");
child1->setParent(root);
Child2 *child2;
child2->setName("Child2");
child2->setParent(node1);
使用這兩種方法,您將獲取一個未初始化的指標 ( child1and child2) 并嘗試取消參考它。
你可能想要這個訂單的東西:
Child1 *child1 = new Child1;
child1->setName("Child1");
// ...
Child2 *child2 = new Child2;
// ...
實際創建圖表需要更多時間,但這至少可以修復您看到的錯誤訊息。為了做一些非常有意義的事情,您將希望每個節點至少包含一個(并且可能是任意數量的)指向子節點的指標。然后,您將希望根的子指標指向 child1,而 child1 的子指標指向 child2(或該順序的某個東西)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/346459.html
