[英]How does this recursive overload of the insertion operator (operator<<) work?
我正在学习递归。 下面是 class 的插入运算符的递归重载,它提供整数的链接列表。 它编译并运行,但我不知道为什么。
重载插入运算符时,我知道您通常会返回一个ostream
引用,以便可以链接调用。 但是,这个 function 不会评估为out << node
,然后是out << out << node
,然后是out << out << out << node
等? 在达到基本情况并开始返回后,您似乎会尝试将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;
}
}
看来您会尝试将 ostream 插入 ostream
没有。 您的<<
运算符返回一个ostream
,但这并不意味着您将其插入另一个 ostream。
您在递归 function 中采取的每一步,都会在 ostream 中插入一些内容并返回相同的 ostream。 看:
out << node->value;
...
out << node->value << ' ';
您总是在 ostream 中插入一些值。
这return out << node;
意味着您将 node->value 插入到 ostream 中,并将 go 插入到下一个节点(如果有下一个节点)。
为了更好地理解,这里是迭代方法,它应该与您的递归方法完全相同:
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.