在 c++ 中,在链表节点上使用括号有什么意义?

What is the significance of using a bracket on the node of the linked list in c++?

本文关键字:什么 c++ 链表 节点      更新时间:2023-10-16

在下面的代码中,mn函数中有一个节点指针naya。在if条件下,naya指针第一次指向 null,我们尝试访问其数据。如果我们尝试执行相同的代码,而不在naya指针周围使用括号,则会产生错误,例如:

prog.cpp: In function ‘void mn(Node*, Node**)’:
prog.cpp:66:50: error: request for member ‘data’ in ‘* naya’, which is of pointer type ‘Node*’ (maybe you meant to use ‘->’ ?)
if(*naya == NULL || temp -> data <= *naya -> data)
^*

但是当我们使用括号时,它工作正常。为什么?

下面是整个代码:

#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next = NULL;
Node(int x) {
data = x;
next = NULL;
}
};
void mn(Node* temp, Node** naya) {
Node* current;
if (*naya == NULL || temp->data <= (*naya)->data) {
temp->next = *naya;
*naya = temp;
} else {
current = *naya;
while (current->next != NULL && (current->next->data < temp->data)) {
current = current->next;
}
temp->next = current->next;
current->next = temp;
}
}
Node* isort(Node* head) {
Node* temp = head;
Node* naya = NULL;
while (temp != NULL) {
Node* nex1 = temp->next;
mn(temp, &naya);
temp = nex1;
}
return naya;
}
void printll(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data;
temp = temp->next;
}
}
int main() {
Node *head = NULL, *temp = NULL;
int a;
cin >> a;
for (int i = 0; i < a; i++) {
int x;
cin >> x;
Node* newnode = new Node(x);
if (head == NULL) {
head = newnode;
temp = head;
} else {
temp->next = newnode;
temp = temp->next;
}
}
head = isort(head);
printll(head);
}

必须以这种方式编写它的原因是因为运算符优先级,它决定了使用哪些操作数执行哪些操作。从该链接中可以看到,默认情况下,"成员访问"或->绑定在"间接(取消引用("或*a之前。通过将取消引用操作括在括号中,可以指定希望在成员访问之前先绑定该操作。

为了更具体,在您的示例中,naya是指向指针的指针。默认情况下,C++首先尝试绑定成员访问操作的操作数(即naya->data(。如果我们要添加括号以使此处的顺序明确,它将如下所示:

*(naya->data)

这具有取消引用naya然后在取消引用的对象中查找data成员变量的效果。取消引用的对象是指针,因此它没有data成员。如果它没有出错,它将继续尝试取消引用数据成员的值(表达式的*部分(。

当你把(*naya)->data,你是在告诉C++它应该用*取消引用naya,而不是像默认那样(naya->data)(*naya)是指向 Node 对象的指针,因此->将成功找到数据成员。