所以我想要用模板定义这个二进制搜索树。这些是标题:
template <class T>
class BSNode
{
public:
BSNode(T data);
BSNode(const BSNode& other);
virtual ~BSNode();
virtual BSNode* insert(T value);
BSNode& operator=(const BSNode& other);
bool isLeaf() const;
T getData() const;
BSNode* getLeft() const;
BSNode* getRight() const;
bool search(T val) const;
int getDepth(const BSNode& root) const;
void printNodes() const;
protected:
T _data;
BSNode* _left;
BSNode* _right;
int _count; // if there are duplicated items.
int BSNode::getCurrNodeDistFromInputNode(const BSNode* node) const; // help func to get depth.
};
但由于某种原因,我总是得到一个&#34;无法匹配的定义&#34; getter中的错误或&#34;使用类模板需要争论列表&#34;
例如,此代码产生&#34;无法匹配定义&#34;错误。
template<class T>
BSNode* BSNode<T>::getLeft() const
{
return this->_left;
}
template<class T>
BSNode* BSNode<T>::getRight() const
{
return this->_right;
}
此代码产生&#34;使用类模板需要参数列表&#34;:
template<class T>
BSNode* BSNode<T>::insert(T value)
{
// check where should insert the node - right or left
if (value < this->_data)
{
if (_left) // if there is already left son
{
_left = _left->insert(value); // recursive call on the left son
}
else
{
_left = new BSNode(value); // add the node as left son
return *this;
}
}
else if (value > this->_data)
{
if (_right) // if there is already right son
{
_right = _right->insert(value); // recursive call on the right son
}
else
{
_right = new BSNode(value); // add the node as right son
return *this;
}
}
else //value == this->_data
{
this->_count++;
return *this;
}
return *this;
}
我很确定我的问题在于签名,但我仍然发布完整的代码。有人可以帮助我理解为什么我会遇到这个问题以及我做错了什么?
答案 0 :(得分:0)
除非编译器已经知道你在BSNode
的上下文中,否则你需要提供模板参数 - 例如
template<class T>
BSNode<T>* BSNode<T>::getLeft() const
{
return this->_left;
}
是的,这感觉有点重复。通过在类定义中定义成员函数,可以减少冗长。 (虽然有些人也因为风格原因而不喜欢这种情况。)