【问题标题】:Function pointer only works inside main?函数指针仅在 main 中有效?
【发布时间】:2019-05-27 13:26:05
【问题描述】:

下面的代码显示了对二叉搜索树的简单插入(手写不是 STL)我在我的 bst 中使用了函数指针,并希望从 main 之外遍历树。我如何让它在 main 之外工作?

我在 tree.inorder() 得到一个错误,说没有重载函数的实例

处理类

#include <iostream>
using namespace std;

void printTree(int & a)
{
    cout << a << endl;
}

handler::handler()
{

}


void handler::printTree()
{   

    BinarySearchTree<int> tree;

    tree.insert(10);
    tree.insert(5);
    tree.insert(2);
    tree.insert(20);

    tree.inorder(printTree);
}

主类

#include <iostream>

#include "BinarySearchTree.h"
#include "handler.h"


int main()
{
    handler handle; 

    handle.printTree();
}
template<class T>
inline void BinarySearchTree<T>::inorder(Node * root, void(*inorderPtr)(T &)) const
{
    if (root != nullptr)
    {
        if (root->left != nullptr)
        {
            inorder(root->left, inorderPtr);
        }
        inorderPtr(root->data);
        if (root->right != nullptr)
        {
            inorder(root->right, inorderPtr);
        }
    }
    else
    {
        cout << "No data" << endl;
    }
}

template<class T>
inline void BinarySearchTree<T>::inorder(void(*inorderPtr)(T &)) const
{
    inorder(this->root, inorderPtr);
}

【问题讨论】:

  • 你知道tree.inorder(printTree);tree.inorder(this-&gt;printTree);是一样的吗?
  • 请在问题中包含确切的错误信息
  • 我不知道,我知道这可能很简单,我不会寻求帮助 D:
  • 严重代码描述项目文件行抑制状态错误(活动) E0304 没有重载函数实例“BinarySearchTree::inorder [with T=int]”与参数列表匹配
  • @Getwrong 你有两个函数名为printTree。试着给一个不同的名字。

标签: c++ function binary-search-tree function-pointers traversal


【解决方案1】:

BinarySearchTree&lt;T&gt;::inorder 被声明为const 因此root-&gt;dataconst 并且您不能调用inorderPtr(root-&gt;data); 因为inorderPtr(又名printTree(int&amp;))需要一个非常量int&amp;

通过修复 const 正确性来修复它。你可以有两个BinarySearchTree&lt;T&gt;::inorder。一个const 采用void(*inorderPtr)(const T &amp;),另一个非常量采用void(*inorderPtr)(T &amp;)

【讨论】:

  • 会试一试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多