[英]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.