【问题标题】:How to get a pointer to point to its grandparent如何获得指向其祖父母的指针
【发布时间】:2023-03-20 14:46:01
【问题描述】:

我有一个三叉树/图,它的一个孩子需要它的孩子指向它的父母。

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 的左手边语句

【问题讨论】:

  • 'this' 是调用该方法的实例。它与您提到的左值无关。

标签: c++ pointers object graph this


【解决方案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,这样就不会泄露内存了。

我希望这能解决您的问题。如果没有,请告诉我我错过了什么,以便我再试一次。

祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多