[英]How does this recursive overload of the insertion operator (operator<<) work?
I'm in the process of learning about recursion.我正在学习递归。 The below is a recursive overload of the insertion operator for a class which provides a linked list of integers.下面是 class 的插入运算符的递归重载,它提供整数的链接列表。 It compiles and runs, but I'm confused as to why.它编译并运行,但我不知道为什么。
When overloading the insertion operator, I understand that you normally return an ostream
reference so that calls can be chained.重载插入运算符时,我知道您通常会返回一个ostream
引用,以便可以链接调用。 However, wouldn't this function evaluate to something along the lines of out << node
, then to out << out << node
, and then to out << out << out << node
, etc?但是,这个 function 不会评估为out << node
,然后是out << out << node
,然后是out << out << out << node
等? Upon reaching the base case and beginning to return, it seems that you would be trying to insert an ostream
into an ostream
, which should cause an error, should it not?在达到基本情况并开始返回后,您似乎会尝试将ostream
插入ostream
,这应该会导致错误,不是吗?
ostream & operator<<(ostream &out, const IntList &intList) {
if (intList.head != nullptr) out << intList.head;
return out;
}
ostream & operator<<(ostream &out, IntNode *node) {
if (node->next == nullptr) {
out << node->value;
return out;
}
else {
out << node->value << ' ';
node = node->next;
return out << node;
}
}
it seems that you would be trying to insert an ostream into an ostream看来您会尝试将 ostream 插入 ostream
Nope.没有。 Your <<
operator returns an ostream
, but it does not mean that you're inserting it into another ostream.您的<<
运算符返回一个ostream
,但这并不意味着您将其插入另一个 ostream。
every step you take in the recursive function, you insert something in the ostream and return the same ostream.您在递归 function 中采取的每一步,都会在 ostream 中插入一些内容并返回相同的 ostream。 See:看:
out << node->value;
...
out << node->value << ' ';
you always insert some value into the ostream.您总是在 ostream 中插入一些值。
this return out << node;
这return out << node;
means thet you will insert node->value into the ostream, and go to the next node (if there is a next node).意味着您将 node->value 插入到 ostream 中,并将 go 插入到下一个节点(如果有下一个节点)。
For better understanding, here the iterative method, it should work exactly as your recursive one:为了更好地理解,这里是迭代方法,它应该与您的递归方法完全相同:
ostream & operator<<(ostream &out, const IntList &intList) {
IntNode *node = intList.head;
while(node->next != nullptr){
out << node->value << ' ';
node = node->next;
}
out << node->value;
return out;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.