【发布时间】:2021-07-29 11:25:18
【问题描述】:
我收到以下错误:e0289 no instance of constructor...matches argument list and c2440: 'initializing' cannot convert from initializer list to BinaryTreeNod
我试图将头指向左右子树。
#include <memory>
using namespace std;
template <typename T>
struct BinaryTreeNode{
T data;
unique_ptr<BinaryTreeNode<T>> left, right;
explicit BinaryTreeNode(const T& data) : data(data) {}
BinaryTreeNode(T data, unique_ptr<BinaryTreeNode<T>> left,
unique_ptr<BinaryTreeNode<T>> right) : data(data), left(move(left)),
right(move(right)) {}
};
int main()
{
BinaryTreeNode<int> subtree_0{ 5 };
BinaryTreeNode<int> subtree_1{ 7 };
BinaryTreeNode<int> head{3, subtree_0, subtree_1 };
}
错误来自 BinaryTreeNode head{3, subtree_0, subtree_1 }; 行。构造函数有问题吗?或者我在尝试这样初始化时做错了什么? 只是想制作一个简单的二叉树(BinaryTree节点的代码来自《编程面试要素》
【问题讨论】:
-
你试过
BinaryTreeNode<int> head{3, &subtree_0, &subtree_1 };吗?不过,std::unique_ptr想要获得所有权(以及delete超出范围时的实例)。这对局部变量来说是个坏主意。 -
在这种情况下,一种可能的解决方法是使用
new创建实例subtree_0和subtree_1并将它们存储为原始指针。你也可以考虑std::make_unique,但你也必须在通话中移动它们。 -
Scheff 是的,我做了,不起作用。
-
是的,我做了,但不起作用。 可能没有从原始指针到
std::unique_ptr的隐式转换。 (必须查看文档...)是的。很明确:std::unique_ptr::unique_ptr。 (这是(3)。) -
我曾经用
std::unique_ptrs 制作了一个示例来处理可以传递实例和临时对象的事情。 (它使用std::unique_ptr的删除器选项来实现这一点。)Demo on coliru。它可以很好地使用,但需要付出一些努力......此外,在我的生产性工作中,我当然有派生类。由于获得临时的所有权需要一个副本,因此我必须添加一个“虚拟副本构造函数”又名。指向指针类的virtual克隆方法。