指向列表中元素VS元素本身的指针
Pointer to the element in the list VS element itself
我在网上找到了这个代码,我需要一点帮助。下面是代码:
#include<iostream>
using namespace std;
/* Linked list structure */
struct list {
struct list *prev;
int data;
struct list *next;
} *node = NULL, *first = NULL, *last = NULL, *node1 = NULL, *node2 = NULL;
class linkedlist {
public:
/* Function for create/insert node at the beginning of Linked list */
void insert_beginning() {
list *addBeg = new list;
cout << "Enter value for the node:" << endl;
cin >> addBeg->data;
if(first == NULL) {
addBeg->prev = NULL;
addBeg->next = NULL;
first = addBeg;
last = addBeg;
cout << "Linked list Created!" << endl;
}
else {
addBeg->prev = NULL;
first->prev = addBeg;
addBeg->next = first;
first = addBeg;
cout << "Data Inserted at the beginning of the Linked list!" << endl;
}
}
我不明白的是,当他正在制作新的节点对象(在这种情况下,它是addBeg),他把一个指针操作符在它前面。我现在是怎么看的,对象创建的时候不应该在名字前不带" * "还有数据,指向下一个的指针和指向前一个的指针,不应该像指向列表中节点的指针那样只包含节点的地址,不包含任何其他数据?如果不是这样,那么是什么使指向列表中节点的指针与节点本身不同呢?
代码中的方法是正确的。您的理解是错误的,不能通过指向该节点的指针访问该节点的数据。
如果addBeg
是指向new list
返回的节点的指针,则该节点的数据可以使用操作符->
访问:
list.data
等价于addBeg->data
。
If that's not the case, then what is the thing that differs the pointer to the node in the list from the node itself ?
=比;addBeg
是指向对象的指针,该对象由new List
返回。
你没有正确解释这个c++声明…代码的含义
list *addBeg = new list;
list* addBeg;
addBeg = new list;
list*
也就是addBeg
的类型。
注意,这些规则确实很奇怪,因为当*
在逻辑上附加到第一个list
以形成类型时,
list *a, b;
将声明a
为"指向列表的指针",而b为"列表的实例"(因此含义附加到list
,但星号本身附加到a
)。
一些程序员在这方面做得很好:
- 他们总是在字体后面加上星号(在左边)
- 它们从不在同一个结构中声明两个变量
根据我的经验,在写了足够的代码之后,这个解释问题将消失,即使是C/c++声明的疯狂语法规则也会很容易阅读(至少在简单的情况下)。
相关文章:
- 调整大小后指向元素值的指针unordered_map有效?
- 当该数组的索引中没有元素时,指针指向什么?
- 如何在基类指针向量的元素上应用重载的多态函数
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 删除指针数组 (C++) 中的元素
- 从指向结构数组的指针中提取元素
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 获取指向指针的指针元素 (c++)
- 经过最后一个数组元素末尾的指针是否应该等于超过整个数组末尾的指针?
- 存储指向动态数组元素的指针
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 如何使用指针C++将元素从2D数组复制到1D数组
- 如何将元素插入到标准::地图的共享指针中?
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在删除之前更新一组元素指针中的元素
- 从 BST 中删除元素(指针错误)
- 避免强制转换容器的元素指针类型
- 填充一个无序的vector元素指针队列
- OpenCV元素指针如何存在于Obj-C类中