首页 > 解决方案 > 操作符“<<”溢出双向链表。C++

问题描述

我无法为我的双向链表创建“<<”的重载函数。

这是我的头文件:


#ifndef SORTEDLIST_H
#define SORTEDLIST_H

#include <iostream>

class SortedList {

private:
    typedef struct node {
        int data;
        node* next;
        node* prev;
    }*nodePtr;

    int theSize;

    nodePtr head;
    nodePtr tail;

public:
    SortedList();
    //~SortedList();
    void insertItem(int inData);
    bool deleteItem(int delData);
    friend ostream& operator <<(ostream& ot, const SortedList& sL);
    int size() const;
    bool empty() const;



};



#endif

这是我的构造函数:

SortedList::SortedList() {
    //Set pointers equal to NULL
    head = NULL;
    tail = NULL;
    theSize = 0;

    head = new node; //create new node of 3 parts: head, data and prev
    tail = new node; //create new node of 3 parts: head, data and prev
    head->next = tail; //next partition points to tail
    head->prev = NULL; //not necessary to put in?
    tail->prev = head; //prev partition points to head
    tail->next = NULL; //not necessary to put in?
    /*temp->next = tail; //access the node the temp pointer is pointing to, set the 'next' part equal to tail*/

}

这是我无法工作的 ostream 重载函数:

ostream& operator<<(ostream& ot, const SortedList& sL)
{
    sL.nodePtr temp;
    temp = sL.head->next;
    while (temp != sL.tail) {
        ot << temp->data << " ";
        temp = temp->next;
    }
    ot << "\n";
}

它一直告诉我 sL.NodePtr、sL.head、sL.tail 无法访问。我确实将它设置为朋友功能,所以我不确定为什么。

标签: c++operator-overloadingdoubly-linked-listostream

解决方案


您的实施存在几个问题operator<<

  • sL.nodePtr需要SortedList::nodePtr

  • while循环都是错误的。它不考虑空列表,并且忽略tail非空列表的节点。哦,等等,您的列表使用虚拟节点作为其headand tail,这是完全没有必要的,只会使类的设计复杂化。完全摆脱假人。

  • 它没有return什么。它需要返回ot

试试这个:

SortedList::SortedList() {
    //Set pointers equal to NULL
    head = NULL;
    tail = NULL;
    theSize = 0;
}

ostream& operator<<(ostream& ot, const SortedList& sL)
{
    SortedList::nodePtr temp = sL.head;
    while (temp) {
        ot << temp->data << " ";
        temp = temp->next;
    }
    ot << "\n";
    return ot;
}

或者,您可以使用for循环而不是while循环:

ostream& operator<<(ostream& ot, const SortedList& sL)
{
    for(SortedList::nodePtr temp = sL.head; temp; temp = temp->next) {
        ot << temp->data << " ";
    }
    ot << "\n";
    return ot;
}

推荐阅读