c++中的指针和引用错误

Pointers and references error in C++

本文关键字:引用 错误 指针 c++      更新时间:2023-10-16

当我尝试编译一个简单的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);

因为leftNoderightNode的类型是A*tree的类型是A,所以没问题。

我建议您将max的参数类型从A&更改为A*,因为这会使代码更干净。