【问题标题】:cannot understand use of this parameter in making a class in c++无法理解在 C++ 中创建类时使用此参数
【发布时间】:2020-07-15 03:38:36
【问题描述】:
class Node {
public:
    int key;
    Node *parent;
    std::vector<Node *> children;

    Node() {
      this->parent = NULL;
    }

    void setParent(Node *theParent) {
      parent = theParent;
      parent->children.push_back(this); // I can't understand this.
    }
};

在函数setParent中,在parent->children.push_back(this)中,我们为什么要传递this作为参数,它会做什么?

【问题讨论】:

标签: c++ tree


【解决方案1】:

this 指针是指向其成员函数当前正在执行的对象的指针。该行代码将this 节点添加到其父级的子级向量中。这是有道理的,因为this 节点是其父节点之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2021-05-22
    • 2011-07-24
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多