【问题标题】:C++ function as parameter errorC++ 函数作为参数错误
【发布时间】: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


【解决方案1】:

错误:无法初始化“void”类型的参数 (*)(BinaryNode, LinkedQueue > &)' 与 'void (string &)' 类型的左值(又名 'void (basic_string, allocator > &)'):第一个参数的类型不匹配 ('BinaryNode, LinkedQueue > &' vs 'string &'(又名'basic_string,分配器> &'))

打破它!

无法初始化类型参数

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

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

预期类型

具有“void (string &)”类型的左值

提供的类型

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

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

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多