【发布时间】:2016-12-05 05:38:06
【问题描述】:
我正在尝试在我创建的二叉搜索树类中遍历的每个节点上运行一个函数。这是遍历 BST 的节点并在每个节点上运行作为参数传入的函数的函数:
template<class ItemType, class OtherType>
void BinarySearchTree<ItemType, OtherType>::Inorder(void visit(BinaryNode<ItemType, OtherType>&), BinaryNode<ItemType, OtherType>* node_ptr) const {
if (node_ptr != nullptr) {
Inorder(visit, node_ptr->GetLeftPtr());
BinaryNode<ItemType, OtherType> node = *node_ptr;
visit(node);
Inorder(visit, node_ptr->GetRightPtr());
} // end if
} // end inorder
这是 BST 类的私有成员函数,因此它被公共成员函数调用:
template<class ItemType, class OtherType>
void BinarySearchTree<ItemType, OtherType>::InorderTraverse(void visit(BinaryNode<ItemType, OtherType>&)) const
{
Inorder(visit, root_);
} // end inorderTraverse
在我的主文件中,我创建了这个函数作为参数传入:
void displayItem(BinaryNode<string, LinkedQueue<int> >& anItem)
遍历是这样调用的:
tree1Ptr->InorderTraverse(displayItem);
当我编译时,我得到了这个错误,我不知道如何修复它。
MainBST.cpp:62:29: error: cannot initialize a parameter of type 'void
(*)(BinaryNode<std::__1::basic_string<char>, LinkedQueue<int> > &)' with
an lvalue of type 'void (string &)' (aka 'void (basic_string<char,
char_traits<char>, allocator<char> > &)'): type mismatch at 1st parameter
('BinaryNode<std::__1::basic_string<char>, LinkedQueue<int> > &' vs
'string &' (aka 'basic_string<char, char_traits<char>, allocator<char> >
&'))
tree1Ptr->InorderTraverse(displayItem);
^~~~~~~~~~~
./BinarySearchTree.h:42:29: note: passing argument to parameter 'visit' here
void InorderTraverse(void visit(BinaryNode<ItemType, OtherType>&)) const;
如果有人理解错误并能够破译并帮助我,我将非常感激。如果您需要我删除更多代码,我很乐意这样做。非常感谢!
【问题讨论】:
-
还有另一个
displayItem吗?编译器很确定displayItem采用string,而不是BinaryNode。也许是陈旧的前向声明? -
天哪,非常感谢。哇,我已经盯着这个项目超过 8 个小时了,我忘记了声明。只是,我更新了定义,但没有更新声明。非常非常感谢。
标签: c++ templates compiler-errors function-parameter