Код проблемы с шаблоном не компилируется - PullRequest
0 голосов
/ 31 октября 2011

Моя проблема в том, что я получаю эту ошибку

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.

Я понимаю, что это может быть шаблон, вызывающий проблемы с областью видимости. Я не хочу, чтобы он думал, что переменная-член Node класса 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);
    }

1 Ответ

2 голосов
/ 31 октября 2011

Проблема в том, что вы вызываете findPaths() (не const член) из функции printPaths() (const член). Вызов не- const члена из const члена не допускается в C ++.

Вы должны переписать код, либо сделавprintPaths() как неконстантные методы или findPaths() и printPath() как const методы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...