谁能解释这行代码的作用?这是关于链接列表

时间:2015-02-18 23:03:54

标签: c++ class operators nodes singly-linked-list

我的教授给了我以下声明,我有一些我需要根据LinkedList的声明编写的函数,但我仍然坚持确定几行代码的作用。我完全了解这些内容;

friend ostream& operator<<( ostream& os, const LinkedList &ll )
{
LinkedList::Node *current;
for (current = ll.head; current != NULL; current = current->next)
os << current->data << " ";
return os;
}

这是完整的代码。

#include <iostream>
#include <cstdlib>
using namespace std;
class LinkedList
{
public:
LinkedList() { head = NULL; } // default constructor makes an empty list
// functions to aid in debugging
// -----------------------------
friend ostream& operator<<( ostream& os, const LinkedList &ll );
void insertHead( int item );
private:
class Node // inner class for a linked list node
{
public:
Node( int item, Node *n ) // constructor
int data; // the data item in a node
Node *next; // a pointer to the next node in the list
};
Node *head; // the head of the list
};
friend ostream& operator<<( ostream& os, const LinkedList &ll )
{
LinkedList::Node *current;
for (current = ll.head; current != NULL; current = current->next)
os << current->data << " ";
return os;
}
void LinkedList::insertHead( int item ) // insert at head of list
{
head = new Node( item, head );
}
LinkedList::Node::Node( int item, Node *n ) {Node::data = item; next = n;}

PS。有人也可以解释一下朋友操作员做了什么,因为我之前从未使用过它?

1 个答案:

答案 0 :(得分:3)

该行

friend ostream& operator<<( ostream& os, const LinkedList &ll )

重载“插入操作符”,因此您可以使用常见的C ++语法显示列表:

std::cout << mylist;

以上一行相当于:

operator<<(std::cout, mylist)

第一个参数的类型为std::ostream,第二个参数的类型为LikedList

运营商需要成为朋友,因为它(可能)需要访问私人/受保护的成员。

有关运算符重载的更多详细信息,请参阅this