模板作用域问题代码无法编译
Template scoping issue code wont compile
我的问题是我得到这个错误
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
方法。
相关文章:
- 在Linux for Windows上编译C++代码时出错
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在程序中编写脚本来编写和编译代码
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 在macos上编译代码的未解析符号
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 使用指针编译代码后,.cpp文件将变为随机字符
- VS Express 无法正确编译代码(?
- 如何在Ubuntu中使用Visual Studio代码编译C++代码
- 使用 Android NDK 使用 clang++ 编译C++代码时对"_Unwind_Resume"的未定义引用
- 无法使用两个包装不同下一层的ssl_stream编译代码
- 编译代码时"[Warning] extra tokens at end of"
- 无法编译代码,因为它已在 C++11 中弃用
- 如何在 Azure 应用服务中使用 cl.exe 编译 C++ 代码并生成可执行文件
- 如何调试编译 c++ 代码的 bazel?
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 编译 C++ 代码后尺寸较大
- 使用用 C++ 和 DDS 编写的 CMAKE 编译代码
- 编译代码时如何不制作二进制文件?
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件