閱讀708 返回首頁    go 阿裏雲 go 技術社區[雲棲]


C++ 中cout<<endl的實現


話說像下麵的語句,應該大家都明白這是通過重載operator <<函數來實現的。

cout<<123;
cout<<"ssss";

但是像

cout<<endl;

是怎樣實現的?

起初猜想endl是一個class或者struct,再通過一個friend函數來實現的。

但是翻下stl的實現,原來endl是一個函數!

template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>& endl(basic_ostream<_CharT, _Traits>& __os) 
{
	return flush(__os.put(__os.widen('\n')));
}

__ostream_type& operator<<(__ostream_type& (*__pf)(__ostream_type&))
{
	return __pf(*this);
}

可見當cout<<endl時,都會調用一次flush函數,這個地方可以注意下。

從下麵的代碼也可以看出實現原理的一二。

cout.operator <<(endl);


最後更新:2017-04-02 16:47:50

  上一篇:go 緩存淘汰算法係列之3——FIFO類
  下一篇:go android開發中WebView的使用(附完整程序)