在 c++ 中,在链表节点上使用括号有什么意义?
What is the significance of using a bracket on the node of the linked list in c++?
在下面的代码中,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 对象的指针,因此->
将成功找到数据成员。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 我应该使用什么来代替void作为变体中的替代类型之一
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用