gpt4 book ai didi

c++ - 使用一些空指针初始化节点

转载 作者:行者123 更新时间:2023-11-28 02:10:58 25 4
gpt4 key购买 nike

我有这个结构:

struct Node{
int key;
Node *parent;
Node *left;
Node *right;
Node(Node *p, Node *l, Node *r){
parent = p;
left = l;
right = r;
}
};

然后我有以下内容,其中 current 是一个 Node*:

current->left = new Node(current, new Node, new Node);

但是我明白了

error: no matching constructor for initialization of 'Node'
current->left = new Node(current, new Node, new Node);
^

有什么问题? new Node返回的不是一个指向未初始化的Node的指针,应该满足构造函数的要求吗?

最佳答案

由于您为 Node 定义了构造函数,因此它不会生成隐式默认构造函数。通过调用不带任何参数的 new Node,您正在尝试调用默认构造函数。

Doesn't new Node return a pointer to an uninitialized Node?

没有。它将构造一个新的 Node 并返回指向它的指针。将 nullptr 作为 Node* 参数传递可能更有意义。

new Node(current, nullptr, nullptr);

关于c++ - 使用一些空指针初始化节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35687141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com