c++ - 有人可以解释这行代码的作用吗?这是关于链接列表

标签 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;}

附言。有人也可以解释一下 friend operator 的作用吗,因为我以前从未使用过它?

最佳答案

线

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

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

std::cout << mylist;

上面一行等同于:

operator<<(std::cout, mylist)

第一个参数是 std::ostream 类型,第二个参数是 LikedList 类型。

运算符(operator)需要成为 friend ,因为它(可能)需要访问私有(private)/ protected 成员。

参见 this有关运算符重载的更多详细信息。

关于c++ - 有人可以解释这行代码的作用吗?这是关于链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595661/

相关文章:

c++ - 在 winforms 中创建可移动和可调整大小的线

c++ - 使用 Eclipse : Bug 在 C++ 中猜谜游戏

python - 类在 2.4 中不起作用

c++ - 尝试在 C++ 中输出数组对象

javascript - JavaScript 中的 instanceof 运算符是什么?

c++ - c++/g++ —编译错误.. fatal error : iostream: No such file or directory compilation terminated

c++ - 分段FTP上传

matlab - 如何在matlab中调用另一个m文件中的类的成员函数?

c - 这个函数 f1() 将如何执行?

python ==语法错误