c++中的指针和引用错误
Pointers and references error in C++
当我尝试编译一个简单的AVL树程序时,我得到这些错误:
no matching function for call to A::max(A*&, A*&)
candidates are: int A::max(A&, A&)
request for member 'levels' in 'b', wich is of non-class type 'A*'
下面是导致问题的方法:
void A::simpleLeftRotation(A & tree){
A* b = tree.leftNode;
tree.leftNode = b->RightNode;
b->rightNode = &tree;
tree.levels = 1 + max(tree.leftNode, tree.rightNode); // Problem 1
b.levels = 1 + max(b.rightNode, tree); // Problem 2
tree = b;
}
下面是我的班级成员:
A* righNode;
A* leftNode;
int levels;
int element;
在这一行:
b.levels = 1 + max(b.rightNode, tree);
如果我用->代替点操作符,我得到:
no matching function for call to A::max(A*&, A&)
candidates are: int A::max(A&, A&)
我不知道我做错了什么。谢谢你。
虽然您没有向我们展示所有类型的声明,但我认为这将解决问题:
tree.levels = 1 + max(*(tree.leftNode), *(tree.rightNode));
b.levels = 1 + max(*(b.rightNode), tree);
最初,当max
函数需要引用时,您正在传递指针。因此,类型不匹配会导致错误。因此,您需要对指针进行解引用,如下所示:
你需要取消对指针的引用:
tree.levels = 1 + max(tree.leftNode, tree.rightNode);
你试图将指针传递给一个以引用作为参数的方法。做的事:
tree.levels = 1 + max( *(tree.leftNode), *(tree.rightNode) );
您应该将max
称为:
max(*(tree.leftNode), *(tree.rightNode));
max(*(b.rightNode), tree);
因为leftNode
和rightNode
的类型是A*
。tree
的类型是A
,所以没问题。
我建议您将max
的参数类型从A&
更改为A*
,因为这会使代码更干净。
相关文章:
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++引用错误
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 只有级联分类器会发出未定义的引用错误
- 2个模板化类的非模板友元函数未定义引用错误
- C/C++ 取消引用错误:在空检查之前取消引用
- 为什么我的C++代码无法编译,出现未定义的引用错误
- 我的代码中C++未定义的引用错误?
- 模板专用化会导致未定义的引用错误
- .cpp文件中未定义的引用错误
- c++ 中目录中文件的未定义引用错误
- Opencv4 使用 pkg-config 给出未定义的引用错误
- 使用Cygwin C++时出现未定义的引用错误,为什么我的文件没有链接?
- 共享指针取消引用错误
- 编译简单的多文件类程序时出现未定义的引用错误
- 模板函数产生未定义的引用错误
- 调用提取重加载器会产生对"运算符"的未定义引用错误>>
- 如何修复"未定义的引用"错误 opencv 和 g++
- 未定义的引用错误,我该怎么办?