C 作为参数错误的功能

C++ function as parameter error

本文关键字:功能 错误 参数      更新时间:2023-10-16

我正在尝试在我制作的二进制搜索树类中遍历的每个节点上运行一个函数。这是遍历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;

如果有人理解错误并可以解读并帮助我,我将非常感谢。如果您需要我丢弃更多代码,我会很高兴这样做。非常感谢!

错误:无法初始化类型'void的参数 (*)(binaryNode,linkedqueue>&amp;)'with with 类型为" void(string&amp;)'的lvalue(aka'void(basic_string,asalocator>&amp;)'):在第一个参数中输入不匹配 ('BinaryNode,Linkedqueue>&amp;'vs 'string&amp;'(又名'Basic_string,分配器> &amp;'))

分解!

无法初始化类型的参数

调用了一个函数,带有错误类型的参数。

'void(*)(binaryNode,linkedqueue>&amp;)'

预期类型

带有'void(字符串&amp;)''

的lvalue

提供了类型

英语翻译:使用void displayItem(std::string &)调用功能,而不是void displayItem(BinaryNode<string, LinkedQueue<int> >& anItem)

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