簡體   English   中英

重載<<鏈表中的運算符

[英]Overloading << operator in linked list

我在為此創建重載編碼時遇到了麻煩。 不太確定從哪里開始甚至如何開始。 我是C ++的新手,即使在閱讀完此書后,也難以理解鏈接列表和節點。 這是我到目前為止所擁有的。

#include "LList.h"
#include <iostream>

using namespace std;

std::ostream& operator<<(ostream& out, const LList& llist);

int main( )
{
LList a;

a.push_back(  "30" );
a.push_front( "20" );
a.push_back(  "40" );
a.push_front( "10" );
a.push_back(  "50" );

cout << "list a:\n" << a << '\n';

return 0;

}

ostream &operator <<( ostream &out, const LList& llist )
{
LList ::          //not sure what to really put from here

return out;
}

這是屏幕截圖 在此處輸入圖片說明

LList.h

#ifndef LList_h
#define LList_h

#include <iostream>
#include "node.h"


class LList
{
public:
LList(void);            //constructor
LList(const LList &);   //copy constructor
~LList();           //destructor
LList *next;            //points to next node
void push_back(const string &str);
void push_front(const string &str);
friend ostream& operator<<(ostream& out, const LList& llist);
LList &operator=(const LList &);        

private:
Node *_head;
Node *_tail;
LList *front;       //points to front of the list

};

inline LList::LList(void)
{
cerr << "default constructor";
}

inline void LList::push_back(const string &str)
{
Node *p = new Node(str);
if (_tail == 0)
{
    _head = _tail = p;
}
else
{
    _tail ->next(p);
    _tail = p;
}
if (_head == 0)
{
    _head = _tail = p;
}
else
{
    _head ->next(p);
    _head = p;
}
}

inline void LList::push_front(const string &str)
{
Node *p = new Node(str);
if (_tail == 0)
{
    _head = _tail = p;
}
else
{
    _tail ->next(p);
    _tail = p;
}
if (_head == 0)
{
    _head = _tail = p;
}
else
{
    _head ->next(p);
    _head = p;
}

}

inline LList::~LList( )
{
Node *p = new Node (str);

if ( _head == 0)
{
    _head = p;
}
else
{
Node *q;
//&Node::next;
    for (q = _head; q->next(); q = q -> next)
{
    //loop until we have
    //q pointing to the last node
}
q->next ( p);   //last node points to p
}       //_uead still points to the first node

}

#endif

我不確定我在哪里。 我只是在嘗試事情,並從我的教授的一些例子中得到一些想法

您基本上只需<<要在重載內部打印的元素。 例如,假設您有一個LList::front()成員函數返回第一個元素,則可以這樣打印:

ostream &operator <<( ostream &out, const LList& llist ) {
  return out << llist.front();
}

顯然,您將希望打印整個列表,而不僅僅是打印第一個元素(並檢查列表是否為空),而且打印方法也相同。 假設LList存儲的元素存在重載,如果沒有,則必須提供。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM