c++ - 模板范围问题代码无法编译

标签 c++ binary-tree

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

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 类的 Node 成员变量我该如何完成这个?

// 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);
    }

最佳答案

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

您必须通过同时设置 printPaths() 来重写代码作为非常量方法或 findPaths()printPath()作为const方法。

关于c++ - 模板范围问题代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7953548/

相关文章:

C++ 从下往上读取文件

c++ - 如果我想让它忽略重复的元素,应该使用哪个 STL 容器?

c++ - 在 std::vector 中搜索一个值的近似值

c++ - 在googlemock中模拟文件写入过程

java - 要打印二叉树的顶 View :递归方法

java - 插入二叉树

c - 如何按名称(字符串)搜索和排序 BST?按队列打印并缩进?

c++ - 使用 std::array::size 实例化 std::array 时出错

java - 为什么将 k-ary 树表示为左子树、右兄弟树?

c++ - 在 C++ 中打印具有指定缩进级别的二叉树