简体   繁体   中英

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. 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. 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? 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 & 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

Nope. Your << operator returns an ostream , but it does not mean that you're inserting it into another ostream.

every step you take in the recursive function, you insert something in the ostream and return the same ostream. See:

out << node->value;
...
out << node->value << ' ';

you always insert some value into the ostream.

this 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM