2016-10-26 53 views
3

我很有趣的問題。C++重載的<<運算符不能正確輸出,除非我包含一個endl

基本上我重載插入操作符來返回我的類的字符串表示形式。但是,除非我包含一個std :: endl,否則程序會終止。

template<class T> 
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) { 

    outs << "queue["; 

    if (!q.empty()) { 
     outs << q.front->value; 

     for (auto i = ++q.begin(); i != q.end(); ++i) 
      outs << ',' << *i; 
    } 
    outs << "]:rear"; 

    return outs; 
} 

int main() { 
    QueueType queueType1; 
    queueType1.enqueue("L"); 
    std::cout << queueType1 << std::endl; 
    return 0; 
} 

上述主要產生的正確的輸出:隊列[L]:後部

但是,如果我從主除去std::endl,程序中斷,併產生什麼。

我不能在重載的方法中包含endl,因爲它爲我的字符串添加了一個額外的字符,我不知道該怎麼辦。有什麼建議麼?

+5

你就錯了。所顯示的代碼沒有任何問題,但是,如果您願意,可以使用'outs << std :: flush;'顯式刷新流緩衝區。 –

+0

複製到https://stackoverflow.com/questions/22026751/c-force-stdcout-flush-print-to-screen – Mine

回答

1

正如@samevarshavchik所示,使用std::flush而不是std::endl來完成所需的輸出。這可以在主做:

int main() { 
    QueueType queueType1; 
    queueType1.enqueue("L"); 
    std::cout << queueType1 << std::flush; 
           /*^^^here^^^*/ 
    return 0; 
} 

或者您的超載函數中:

template<class T> 
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) { 

    outs << "queue["; 

    if (!q.empty()) { 
     outs << q.front->value; 

     for (auto i = ++q.begin(); i != q.end(); ++i) 
      outs << ',' << *i; 
    } 
    outs << "]:rear" << std::flush; 
         /*^^^here^^^*/ 
    return outs; 
}