我有一个三级树/图,其中一个孩子需要孩子指回其父级。
class TTree
{
public:
tTree();
~tTree();
TTree *back;
TTree *forward;
TTree *left;
TTree *right;
int numsteps;
bool ifVisited = false;
bool ifExpended = false;
void insert(int steps, TTree *direction);
}
在插入*back
中必须指向自身。
TTree::insert(int steps, TTree *direction){
this->direction = TTree();
this->direction->numsteps = steps;
this->direction->back = this;
this->direction->forward = NULL;
this->direction->left = NULL;
this->direction->right = NULL;
}
我想出了这个,但是我不确定this->direction->back = this
右手this
是否会指向自己作为调用函数的对象,或者它会引用左手语句this->direction->back
答案 0 :(得分:-1)
如果我理解正确,根节点back
指针应该是NULL
,表示它是根,并且它没有父节点。插入新节点时,您必须让父级设置子级,并使用父级this
作为子级back
的值。
//called within parent node
TTree::insert(int steps, TTree *direction){
direction = new TTree();
direction->numsteps = steps;
direction->back = this;
direction->forward = NULL;
direction->left = NULL;
direction->right = NULL;
}
您不会将this
用于direction
变量,因为它不是this
引用的对象的成员,它是指向this
内对象的指针这不是一回事。
我也相信你会想在行direction = TTree();
上使用动态内存,因为看起来你正试图将一个临时对象分配给一个无效的指针。所以请使用direction = new TTree();
请记住稍后再调用delete
,这样就不会泄漏内存。
我希望这能解决你的问题。如果没有,请让我知道我错过了什么,所以我可以再拍一次。
祝你好运