我找不出这段代码为什么会出现错误。 引发错误的行在行尾注释。 错误信息如下所示。
我正在尝试实现一个简单的二进制搜索树BST
,它有一个基类Tree
。 这些类利用node
类,它表示树中的单个节点。
template <typename Value> class Node { private: Value value = 0; Node<Value>* leftChild = NULL; Node<Value>* rightChild = NULL; public: Node(Value value) { this->value = value; } ~Node() { delete leftChild; delete rightChild; } Value GetValue() const { return value; } void SetValue(Value value) { value = value; } Node<Value>* GetLeftChild() const { return leftChild; } void SetLeftChild(Node<Value>* leftChild) { leftChild = leftChild; } Node<Value>* GetRightChild() const { return rightChild; } void SetRightChild(Node<Value>* rightChild) { rightChild = rightChild; } }; template <typename Value> class Tree { protected: Node<Value>* root = NULL; }; template <typename Value> class BST : public Tree<Value> { private: // In main, I call bst._insertIntoSubtree(tree->root, newNode) Node<Value>* _insertIntoSubtree(Node<Value>* root, Node<Value>* newNode) { if (root) { if (root->GetValue() < newNode->GetValue()) { root->SetRightChild(_insertIntoSubtree(root->GetRightChild(), newNode->GetValue())); // Error } else { root->SetLeftChild(_insertIntoSubtree(root->GetLeftChild(), newNode->GetValue())); // Error } return root; } else { return newNode; } } }
完整错误消息:
In file included from main.cpp:6: Tree.hpp: In instantiation of 'Node<Value>* BST<Value>::_insertIntoSubtree(Node<Value>*, Node<Value>*) [with Value = int]': Tree.hpp:128:9: required from 'void BST<Value>::insert(Value) [with Value = int]' Tree.hpp:122:13: required from 'BST<Value>::BST(std::vector<_Tp>) [with Value = int]' main.cpp:17:38: required from here Tree.hpp:108:17: error: invalid conversion from 'int' to 'Node<int>*' [-fpermissive] root->SetRightChild(_insertIntoSubtree(root->GetRightChild(), newNode->GetValue())); ^~~~ Tree.hpp:105:69: note: initializing argument 2 of 'Node<Value>* BST<Value>::_insertIntoSubtree(Node<Value>*, Node<Value>*) [with Value = int]' Node<Value>* _insertIntoSubtree(Node<Value>* root, Node<Value>* newNode) { ~~~~~~~~~~~~~^~~~~~~ Tree.hpp:110:17: error: invalid conversion from 'int' to 'Node<int>*' [-fpermissive] root->SetLeftChild( ^~~~ Tree.hpp:105:69: note: initializing argument 2 of 'Node<Value>* BST<Value>::_insertIntoSubtree(Node<Value>*, Node<Value>*) [with Value = int]' Node<Value>* _insertIntoSubtree(Node<Value>* root, Node<Value>* newNode) {
问题解决了。 请参阅注释。