簡體   English   中英

插入運算符 (operator<<) 的這種遞歸重載是如何工作的?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM