问题描述
我之前在 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.
这篇关于为什么链表使用指针而不是将节点存储在节点内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)