【问题标题】:can someone explain to what this line of code does? It is about Linked Lists [closed]有人可以解释这行代码的作用吗?这是关于链接列表[关闭]
【发布时间】:2015-04-20 03:57:59
【问题描述】:

我的教授给了我以下声明,我需要根据 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。谁能解释一下朋友运营商是做什么的,因为我以前从未使用过它?

【问题讨论】:

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


【解决方案1】:

线

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

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

std::cout << mylist;

上面的行相当于:

operator<<(std::cout, mylist)

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

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

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

【讨论】:

  • @zeDante 对于有问题的代码的另一部分,您可能想了解for 循环的工作原理。有关该主题的一些信息,请参阅this page。我将把那行代码的链表部分留给你,因为类主题似乎是链表。
  • 非常感谢,现在这真的更有意义了。最后一个问题只是为了澄清,做 os data
  • 是的,os代表函数的输入流,通过引用传递。因此,当您说cout &lt;&lt; my_list 时,cout 将作为第一个参数传递给operator&lt;&lt;。在函数内部,它被称为os。还要注意,不一定要用cout,你也可以用一个文件out_file &lt;&lt; my_list,内容会发送到文件,因为后者也是一个ostream。这就是使用继承和编写一个适用于设计良好的层次结构基础的函数的美妙之处。
  • 谢谢。你是救生员
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 2015-10-28
  • 2014-05-18
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多