posts - 134,comments - 22,trackbacks - 0
以前一直没有关心std::endl的工作机制,最近突然想一窥究竟,于是下载了sgi的stl(http://www.sgi.com/tech/stl/)实现,
于是恍然大悟,对其实现者真是敬佩。

在文件Ostream中class basic_ostream 有如下成员函数:

 basic_ostream& operator<< (basic_ostream& (*__f)(basic_ostream&))
    { return __f(*this); }

 basic_ostream& operator<< (_Basic_ios& (*__f)(_Basic_ios&))
    { __f(*this); return *this; }

 basic_ostream& operator<< (ios_base& (*__f)(ios_base&))
    { __f(*this); return *this; }

然后有如下全局函数:
template <class _CharT, class _Traits>
inline basic_ostream<_CharT, _Traits>&
endl(basic_ostream<_CharT, _Traits>& __os) {
  __os.put(__os.widen('\n'));
  __os.flush();
  return __os;
}

可见原来我们经常使用的cout<<.....<<endl中的endl竟然是一个函数指针,由此我们还可以找到如下定义:

// basefield manipulators, section 27.4.5.3
inline ios_base& dec(ios_base& __s)
  { __s.setf(ios_base::dec, ios_base::basefield); return __s; }

inline ios_base& hex(ios_base& __s)
  { __s.setf(ios_base::hex, ios_base::basefield); return __s; }

inline ios_base& oct(ios_base& __s)
  { __s.setf(ios_base::oct, ios_base::basefield); return __s; }

原来这些我们经常见到的C++流输出格式符居然都是一些函数,都是通过重载<<操作符来实现的。
http://www.cppblog.com/luke/archive/2009/04/01/78572.html
posted on 2009-11-15 12:21 何克勤 阅读(291) 评论(0)  编辑  收藏 所属分类: C/C++

只有注册用户登录后才能发表评论。


网站导航: