函数指针仅在 main 内部工作



下面的代码显示了对二叉搜索树的简单插入(手写不是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);
}

BinarySearchTree<T>::inorder 被声明const因此root->dataconst的,你不能调用inorderPtr(root->data);,因为inorderPtr(又名 printTree(int&) (需要一个非常量int&

通过修复常量正确性来修复它。你可以有两个BinarySearchTree<T>::inorder.一个const采取void(*inorderPtr)(const T &),另一个不常量,采取void(*inorderPtr)(T &).

最新更新