模板作用域问题代码无法编译

Template scoping issue code wont compile

本文关键字:编译 代码 问题 作用域      更新时间:2023-10-16

我的问题是我得到这个错误

binarytree.cpp: In member function ‘void BinaryTree<T>::printPaths(const BinaryTree<T>::Node*) const [with T = int]’:
binarytree.cpp:88:   instantiated from ‘void BinaryTree<T>::printPaths() const [with T = int]’
main.cpp:113:   instantiated from ‘void printTreeInfo(const BinaryTree<T>&, const std::string&, const std::string&) [with T = int]’
main.cpp:47:   instantiated from here
binarytree.cpp:116: error: passing ‘const BinaryTree<int>’ as ‘this’ argument of ‘void BinaryTree<T>::findPaths(BinaryTree<T>::Node*, int*, int) [with T = int]’ discards qualifiers
compilation terminated due to -Wfatal-errors.

我明白,它可能是模板,导致范围问题,我不希望它认为BinaryTree类的节点成员变量,我怎么做到这一点?

// printPaths()
    template <typename T>
    void BinaryTree<T>::printPaths() const
    {
        printPaths(root);
    }
    template <typename T>
    void BinaryTree<T>::printPath(int path[],int n)
    {
        for(int i = 0; i<n; i++)
            cout << (char)path[i] << " ";
            cout << endl;
    }
    template<typename T>
    void BinaryTree<T>::findPaths(Node * subroot, int path[], int pathLength)
    {
        if(subroot == NULL) return;
        path[pathLength] = subroot->elem;
        pathLength++;
        if(subroot->left == NULL && subroot->right = NULL)
            printPath(path,pathLength);
            else
            {
                findPaths(subroot->left, path, pathLength);
                findPaths(subroot->right,path,pathLength);
            }
    }
    template<typename T>
    void BinaryTree<T>::printPaths(const Node* subroot) const
    {
        int path[100];
        findPaths(subroot,path,0);
    }

问题是您正在从printPaths() (const成员)函数调用findPaths()(非const成员)。 c++不允许从const member调用non const member

您必须重写代码,要么将printPaths()作为非const方法,要么将findPaths()printPath()作为const方法。