无法分配给链表中的对象
Can't assign to object in linked list
头部和尾部正在填充,并打印出值,但由于某种原因nodePtr保持空。当我在VS2015中调试时,头和尾号被填充,而字段保持为空
这是Linked_List
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <iostream>
class LinkedList
{
public:
struct Node
{
int number;
Node * next;
Node() : number(NULL), next(NULL) {};
Node(int number_, Node * next_ = NULL)
{
number = number_;
next = next_;
}
}*head, *tail, *nodePtr;
LinkedList();
~LinkedList();
void add(int num);
friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
private:
int size;
};
#endif // _LINKED_LIST_
实现文件
include "linkedlist.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList() : head(NULL), tail(NULL), nodePtr(NULL)
{
nodePtr = new Node();
}
LinkedList::~LinkedList()
{
Node * curr, *temp;
curr = head;
temp = head;
while (curr != NULL)
{
curr = curr->next;
delete temp;
temp = curr;
}
}
void LinkedList::add(int num)
{
Node * newNode = new Node();
newNode->number = num;
cout << newNode->number;
if (head == NULL)
{
head = newNode;
tail = newNode;
size++;
}
else
{
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
size++;
}
//cout << nodePtr->number; //empty, or some random
//just some tests
cout << head->number;
if (head->next != NULL)
{
cout << head->next->number;
}
cout << tail->number;
cout << endl;
}
std::ostream & operator<<(std::ostream & out, LinkedList & list)
{
out << list.nodePtr->number << endl;
return out;
}
主.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
int main()
{
int num;
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
cout << list;
cout << "Press 1: ";
cin >> num;
return 0;
}
你在这里错过了一个基本概念。nodePtr
不是什么神奇的节点,它知道所有其他节点,或者知道链表,或者可以用来打印它们的所有数字。
执行此操作时:
out << list.nodePtr->number << endl;
您所做的只是输出分配新Node
并在nodePtr
中存储指针时初始化的值:
nodePtr = new Node();
这调用了Node
的默认构造函数,该构造函数将nodePtr->number
设置为零。 (旁注,您将其初始化为NULL
,而不是0
- 您不应该将整数类型与指针类型混合使用,因此请将其更改为将值初始化为 0)。
它的值保持为 0,因为您从不修改它。nodePtr
总是指向那个节点,因为你从来没有修改过nodePtr
。
您真正想做的是打印出您的列表。 让我建议一种正常的方法来做到这一点,从head
开始并遵循节点链接:
std::ostream & operator<<(std::ostream & out, const LinkedList & list)
{
for( Node *node = list.head; node != nullptr; node = node->next )
{
out << node->number << std::endl;
}
return out;
}
最后,我建议你从课堂上完全删除nodePtr
。
你只在构造函数中使用nodePtr,你永远不会改变它的值。
相关文章:
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表包含 c++ 中不同的派生类对象
- 如何深度复制链表对象指针
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 节点链表中的对象
- 按引用或值传递链表对象更好吗?
- 基于范围的 for 循环,用于包含C++中的指针的自定义链表,仅返回对象
- C++ 如何创建链表的副本作为类对象
- 无法分配给链表中的对象
- C++ 链表:"->"运算符无法更改节点对象的内部值
- 具有自己的链表的对象
- 存储类对象的C++模板链表-未处理的异常访问冲突读取位置
- 从链表访问对象(自定义实现)
- 创建面向对象的链表时出现编译问题(编译器错误C2664)
- 对象数组作为链表中的字符数组 - 我对对齐的假设是否有效
- 将对象添加到链表错误 [C++]
- C++ 链表:对象的索引
- 如何将链表对象写入文件
- 如何在C++中将对象转换为链表