C++函数作为参数错误

C++ function as parameter error

我正在尝试 运行 在我创建的二进制搜索树 class 中遍历的每个节点上的一个函数。下面是遍历 BST 节点的函数和 运行s 作为每个节点上的参数传入的函数:

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 class 的私有成员函数,因此它被 public 成员函数调用:

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;

如果有哪位大神能看懂错误并破译并帮助我,将不胜感激。如果您需要我删除更多代码,我会很乐意这样做。非常感谢!

error: cannot initialize a parameter of type 'void (*)(BinaryNode, LinkedQueue > &)' with an lvalue of type 'void (string &)' (aka 'void (basic_string, allocator > &)'): type mismatch at 1st parameter ('BinaryNode, LinkedQueue > &' vs 'string &' (aka 'basic_string, allocator > &'))

打破它!

cannot initialize a parameter of type

使用错误类型的参数调用函数。

'void (*)(BinaryNode, LinkedQueue > &)'

预期类型

with an lvalue of type 'void (string &)'

提供的类型

英文翻译:函数是用 void displayItem(std::string &) 调用的,而不是 void displayItem(BinaryNode<string, LinkedQueue<int> >& anItem)

解决方案:确保在首次使用前声明 void displayItem(BinaryNode<string, LinkedQueue<int> >& anItem)。可能搜索并删除或重命名 void displayItem(std::string &) 以防止将来混淆。