[英]Using overloaded << operator with pointer of class
I'm defining a LinkedList class, which makes use of a separately-defined Node class. 我正在定义一个LinkedList类,该类使用了单独定义的Node类。 Each Node has a pointer to the next node.
每个节点都有一个指向下一个节点的指针。
In the Node class, I have friend ostream& operator<<(ostream& ostr, const Node<T>& m);
在Node类中,我有
friend ostream& operator<<(ostream& ostr, const Node<T>& m);
In the LinkedList class, I have head, which is a pointer to the first Node. 在LinkedList类中,我有一个头,它是第一个Node的指针。
How can I define a print function for LinkedList that will iteratively call the overloaded << operator for each node in the list? 如何为LinkedList定义一个打印函数,该函数将为列表中的每个节点迭代调用重载的<<运算符? SO far I have
到目前为止,我有
void LinkedList::print() {
Node* search = head;
while(search) {
cout << //print stuff here
search = search->getNext();
}
cout << endl;
}
Fisrtly I would like to refer you to a developed question: 首先,我想向您介绍一个已发展的问题:
Operator overloading on class templates 运算符在类模板上的重载
Secondly, here some stuff I came up with: 其次,在这里我想到了一些东西:
By writing: 通过写:
friend ostream& operator<<(ostream& ostr, const LinkedList<T>& m);
in class declaration you informed the compiler that you are going to use overloading of operator << to do something with the class(print it). 在类声明中,您通知编译器您将使用运算符<<的重载来对类进行某些操作(打印)。 Now you have to define the function.
现在,您必须定义函数。
Please note that it is a global function, not a class method. 请注意,它是一个全局函数,而不是类方法。
Also I "fixed" two bugs in your code. 我也“修复”了您代码中的两个错误。 One in the function declaration, in which the
LinkedList
should be an argument. 函数声明中的一个,其中
LinkedList
应该作为参数。 Intuitive => Because you want to print the list not the node. 直观=>因为您要打印列表而不是节点。
Second was in first line in which you have to take the m's head
member's adress. 第二是在第一行中,您必须获取M的
head
成员的地址。 In your "C'ish" implementation it is necessary. 在“ C'ish”实现中,这是必要的。
ostream& operator<<(ostream& ostr, const LinkedList<T>& m) {
Node* search = &(m.head); // You have to take the adrress of the head
while(search) {
ostr << //print stuff here
search = search->getNext();
}
ostr << endl;
return ostr;
}
This might seem a quite odd to return the stream but it actually makes sense in statement like: 返回流似乎很奇怪,但实际上在如下语句中有意义:
LinkedList<Banana> bananas;
LinkedList<Apple> apples;
cout << bananas << apples;
Because bananas
takes cout
, uses it and then return
s it to be used by apples
. 因为
bananas
需要cout
,将其使用,然后再将其return
以供apples
。
Hope I didn't obfuscated it too much or made any mistakes. 希望我不要混淆太多,也不要犯任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.