【发布时间】:2021-10-22 12:02:40
【问题描述】:
我正在尝试用 C++ 编写一个列表类,我想重载 << 运算符。但是,当我将列表对象传递给运算符函数时,会更改对象中的值。 StackOverflow 上的其他问题并没有帮助解决这个问题。
多余的代码已从以下内容中删除:
LinkedList.h:
#include "Node.h"
#include <iostream>
class LinkedList {
public:
Node* head;
Node* tail;
int size;
LinkedList();
void push(int data);
friend std::ostream& operator<<(std::ostream& os, const LinkedList& list);
};
这是 LinkedList.cpp:
#include "LinkedList.h"
LinkedList::LinkedList() {
head = nullptr;
tail = nullptr;
size = 0;
}
void LinkedList::push(int data) {
Node newNode = Node(data);
if (size == 0) {
head = &newNode;
tail = &newNode;
} else {
tail->next = &newNode;
newNode.prev = tail;
tail->next = &newNode;
}
size++;
}
std::ostream& operator<<(std::ostream& os, const LinkedList& list) {
os << "[";
os << list.head->data;
os << "]";
return os;
}
(目前我只希望它输出列表中第一个元素中的数据)
这里是驱动代码:
#include "LinkedList.h"
int main() {
LinkedList lis = LinkedList();
lis.push(5);
std::cout << lis;
}
请轻点,我是 C++ 新手。
编辑: 抱歉,这里是 Node.h:
#pragma once
class Node {
public:
int data;
Node* next;
Node* prev;
Node(int data);
};
和 Node.cpp
#include "Node.h"
Node::Node(int initdata) {
data = initdata;
next = nullptr;
prev = nullptr;
}
我还添加了 LinkedList.cpp 的其余部分。我对上述代码的预期输出是[5],因为我将 5 推到列表中,然后输出它(或者至少尝试输出)。
【问题讨论】:
-
什么是
Node?什么是LinkedList()。push是什么?请edit 并提供minimal reproducible example,我们可以实际编译的东西。还请告诉我们您期望的输出以及获得的输出。 -
去掉了太多多余的代码,因为这段代码没有编译通过。或者,还没有删除足够多的多余代码,因为这段代码无法编译。
-
我们需要查看
LinkedList()和push的定义,以帮助您调试隐藏在其中一个或两个中的内存损坏错误。 -
你在这里存储一个局部变量的地址。
head = &newNode;。局部变量一旦超出范围就无法再访问。 -
@Jabberwocky 我不明白?
head不是局部变量,它是lis的属性,所以它应该仍然可以通过lis.head访问,对吧?还是我错过了什么?我的调试器告诉我push函数没有问题。