[英]c++ initializing a binary tree node
我收到這些錯誤:e0289 沒有構造函數實例...匹配參數列表和 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 節點的代碼來自“編程面試元素”
std::unique_ptr
不支持隱式指針到唯一指針的轉換,但它有一個顯式構造函數可以這樣做。 但是不建議為其分配堆棧分配的指針,因為它可能稍后會嘗試刪除它。
為了解決這個問題,我們需要用唯一的指針來制作這兩個節點。
std::unique_ptr<BinaryTreeNode<int>> subtree_0 = std::make_unique<BinaryTreeNode<int>>(BinaryTreeNode<int>(5));
std::unique_ptr<BinaryTreeNode<int>> subtree_1 = std::make_unique<BinaryTreeNode<int>>(BinaryTreeNode<int>(7));
但正如規范所述,您不能復制任何唯一指針。 這意味着我們需要將這兩個指針移動到樹節點 object。 為此,我們需要在構造函數中接受它們作為右值。 然后我們可以毫無問題地將指針移動到 object。
template <typename T>
struct BinaryTreeNode {
...
BinaryTreeNode(T data, std::unique_ptr<BinaryTreeNode<T>>&& left,
std::unique_ptr<BinaryTreeNode<T>>&& right) : data(data), left(std::move(left)), right(std::move(right)) {}
};
int main()
{
std::unique_ptr<BinaryTreeNode<int>> subtree_0 = std::make_unique<BinaryTreeNode<int>>(BinaryTreeNode<int>(5));
std::unique_ptr<BinaryTreeNode<int>> subtree_1 = std::make_unique<BinaryTreeNode<int>>(BinaryTreeNode<int>(7));
BinaryTreeNode<int> head{ 3, std::move(subtree_0), std::move(subtree_1) };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.