如何获得指向其祖父母的指针

时间:2014-05-06 23:13:52

标签: c++ pointers object graph this

我有一个三级树/图,其中一个孩子需要孩子指回其父级。

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

1 个答案:

答案 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,这样就不会泄漏内存。

我希望这能解决你的问题。如果没有,请让我知道我错过了什么,所以我可以再拍一次。

祝你好运