将对象传递给 << 重载改变 C++ 中对象中的数据

Passing object to << overload in alters data in object in C++

我正在尝试用 C++ 编写列表 class,我想重载 << 运算符。但是,当我将列表对象传递给运算符函数时,更改了对象内的值。 Whosebug 上的其他问题并没有帮助解决这个问题。 多余的代码已从以下内容中删除:

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 推到列表中然后输出它(或者,至少,尝试输出)。

您需要使用 new 运算符分配新节点。

这是您更正后的代码:

#include <iostream>

class Node {
public:
  int data;
  Node *next;
  Node *prev;

  Node(int data);
};  

Node::Node(int initdata) {
  data = initdata;
  next = nullptr;
  prev = nullptr;
}

class LinkedList {
public:
  Node *head;                       // <<<<<<<<<<< change here
  Node *tail;                       // <<<<<<<<<<< change here
  int size;

  LinkedList();
  void push(int data);

  friend std::ostream& operator<<(std::ostream& os, const LinkedList& list);
};

LinkedList::LinkedList() {
  head = nullptr;
  tail = nullptr;
  size = 0;
}

void LinkedList::push(int data) {
  Node *newNode = new Node(data);   // <<<<<<<<<<< change here
  if (size == 0) {
    head = newNode;                 // <<<<<<<<<<< change here
    tail = newNode;                 // <<<<<<<<<<< change here
  }
  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;
}

int main() {
  LinkedList lis = LinkedList();
  lis.push(5);
  std::cout << lis;
}