我的问题是我收到此错误
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);
}
答案 0 :(得分:2)
问题是您是从findPaths()
(const
成员)功能调用printPaths()
(非const
成员)。 C ++不允许从 const 成员调用非 const 成员。
您必须通过将printPaths()
作为非const方法或findPaths()
和printPath()
作为const
方法来重新编写代码。