gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:44:56 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com