Why do linked lists use pointers instead of storing nodes inside of nodes(为什么链表使用指针而不是将节点存储在节点内)
问题描述
我之前在 Java 中广泛使用过链表,但我对 C++ 非常陌生.我正在使用在项目中提供给我的这个节点类很好
I've worked with linked lists before extensively in Java, but I'm very new to C++. I was using this node class that was given to me in a project just fine
class Node
{
public:
Node(int data);
int m_data;
Node *m_next;
};
但是我有一个问题没有得到很好的回答.为什么要使用
but I had one question that wasn't answered very well. Why is it necessary to use
Node *m_next;
指向列表中的下一个节点而不是
to point to the next node in the list instead of
Node m_next;
我理解最好使用指针版本;我不会争论事实,但我不知道为什么这样更好.关于指针如何更好地进行内存分配,我得到了一个不太明确的答案,我想知道这里是否有人可以帮助我更好地理解这一点.
I understand that it is better to use the pointer version; I'm not going to argue facts, but I don't know why it's better. I got a not so clear answer about how the pointer is better for memory allocation, and I was wondering if anyone here could help me understand that better.
推荐答案
这不仅更好,而且是唯一可能的方法.
It's not just better, it's the only possible way.
如果你在自身内部存储了一个 Node object,那么 sizeof(Node) 会是什么?它将是 sizeof(int) + sizeof(Node),这将等于 sizeof(int) + (sizeof(int) + sizeof(Node)),即将等于 sizeof(int) + (sizeof(int) + (sizeof(int) + sizeof(Node))) 等到无穷大.
If you stored a Node object inside itself, what would sizeof(Node) be? It would be sizeof(int) + sizeof(Node), which would be equal to sizeof(int) + (sizeof(int) + sizeof(Node)), which would be equal to sizeof(int) + (sizeof(int) + (sizeof(int) + sizeof(Node))), etc. to infinity.
这样的对象是不可能存在的.这是不可能.
An object like that can't exist. It's impossible.
这篇关于为什么链表使用指针而不是将节点存储在节点内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么链表使用指针而不是将节点存储在节点内
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
