我的printTree函数在重载的ostream运算符中不起作用。错误和代码如下。
错误代码:C3861('printTree':找不到标识符)
描述:'printTree':该函数未在模板定义上下文中声明,只能通过以下方式找到实例上下文中与参数相关的查找
类声明
#pragma once
#include "BSTNode.h"
#include <iostream>
template <typename T> class BST;
template <typename T>
std::ostream& operator<<(std::ostream& out, const BST<T>& rhs);
template <typename ItemType>
class BST
{
private:
BSTNode<ItemType>* root;
BSTNode<ItemType>* insert(ItemType* &data, BSTNode<ItemType>* root);
BSTNode<ItemType>* remove(const ItemType &x, BSTNode<ItemType>* root);
BSTNode<ItemType>* findMin(BSTNode<ItemType>* root) const;
BSTNode<ItemType>* findMax(BSTNode<ItemType>* root) const;
bool search(const ItemType &data, BSTNode<ItemType>* root) const;
void destroyTree(BSTNode<ItemType>* root); //for destructor
BSTNode<ItemType>* clone(BSTNode<ItemType>* root) const;
void printTree(std::ostream& out, BSTNode<ItemType>* root) const;
public:
BST();
~BST();
BST(const BST &rhs);
BSTNode<ItemType>* getRoot() const {return root;}
bool isEmpty();
void insert(ItemType* &data);
bool remove(const ItemType &x);
ItemType findMin() const;
ItemType findMax() const;
bool search(const ItemType &data) const;
friend std::ostream& operator<< <>(std::ostream & out ,const BST<ItemType> &rhs);
void printTree (std::ostream &out = std::cout) const;
};
相关方法
template <typename ItemType>
void BST<ItemType>::printTree(std::ostream& out, BSTNode<ItemType>* root) const
{
if (root != nullptr)
{
printTree(out, root->getLeft());
out << *(root->getData()) << std::endl;
printTree(out, root->getRight());
}
}
template <typename ItemType>
std::ostream& operator << <>(std::ostream & out , const BST<ItemType> &rhs)
{
printTree(out, rhs.getRoot());
return out;
}
已解决:
需要在运算符重载定义中将调用对象添加到printTree函数中
template <typename ItemType>
std::ostream& operator << <>(std::ostream & out , const BST<ItemType> &rhs)
{
rhs.printTree(out, rhs.getRoot());
return out;
}
std::ostream& operator<<(std::ostream& out, const BST<T>& rhs);
friend std::ostream& operator<< <>(std::ostream & out ,const BST<ItemType> &rhs);
有区别>,所以我不确定这是否是您的错误。与方法相同。