cout<<endl 本质解析
来源:互联网 发布:安全评价行业 知乎 编辑:程序博客网 时间:2024/05/16 04:15
C++中
cout《《endl很好用,效果上是换行加缓冲区刷新,比起C中的printf(‘\n’)麻烦的格式设置要方便很多。
但是cout《《endl是怎么实现的?endl是个什么东西?
C++中,有一种对象叫操控器(manipulators),操控器是专门用来操控stream的对象,常常只会改变输入或格式化输出的解释方式,在C++标准中,已经预定义好几种操控器,常见的有:
flush 刷新output缓冲区,将内容写入输出设备endl 向缓冲区插入换行符号并刷新,将内容写入输出设备ends 向缓冲区插入字符串终止符号,通常是'\0'ws 读取时忽略空格
下面以常用的endl为例进行说明。
在中,可以见到endl的定义为:
/** * @brief Write a newline and flush the stream. * * This manipulator is often mistakenly used when a simple newline is * desired, leading to poor buffering performance. See * http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html * for more on this subject. */ template<typename _CharT, typename _Traits> inline basic_ostream<_CharT, _Traits>& endl(basic_ostream<_CharT, _Traits>& __os) { return flush(__os.put(__os.widen('\n'))); }
可见endl实际上是一个已经已经定义好的全局的模版函数,它的形式可以简单的认为是
ostream& endl(ostream& strm)
而在ostream类中,有一种输出重载方式如下:
ostream& ostream::operator<<(ostream& (*op)(ostream&)){ return (*op)(*this);}
这个重载函数的参数是一个函数指针,而且该函数的形式正好是上面已经预定义好的操控器endl,因此,当出现cout<
cout<<endl; //ostream函数重载endl(cout); //endl全局函数调用
至此我们就知道了cout<
ostream& endl(ostream& strm){ strm.put('\n'); //向输出流添加换行符 strm.flush(); //刷新输出流 return strm; //返回输出流对象}
其他几种操控器也仅仅是这些执行过程有区别罢了,当然我们也可以自定义操控器,只要满足ostream::operator<<的函数指针参数的格式即可。
结论:endl是C++中的操控器,实质上是一个函数指针。
0 0
- cout<<endl 本质解析
- 关于cout<<1; cout<<endl;和cout<<1<<endl;的解析
- cout<<endl
- cout<<"Hello World"<<endl;
- cout<<endl;什么意思?
- cout << s.c_str() << endl;和cout << s << endl;的区别
- cout<<endl;与cout<<"/n";的区别
- cout < <true?1:"1" < <endl;
- cout < < __FILE__ < < __LINE__ < < __FUNCTION__ < < endl
- C++ 中cout<<endl的实现
- “cout” "endl“: 未声明的标识符”是怎么回事
- 语句std::cout<<std::endl的作用
- C++中如何理解cout endl
- std::cout和std::endl是什么意思?
- cout<<"a1="<<a<<endl; cout<<"a2="<<-0x80000000<<endl;
- C++中endl的本质是什么
- C++中endl的本质是什么
- 在 Python中使用 cout << 'Hello,world!' << endl
- 创建音乐盒播放器
- pthread 线程库编程 一:线程与互斥锁 mutex_lock
- [UIApplication sharedApplication].keyWindow 添加视图无效,解决方案。
- 字符串的最长公共子序列问题
- 软件工程—思考项目开发那些事(一)
- cout<<endl 本质解析
- C语言编程入门——程序练习(下)
- 数据库优化 in 软件生命周期的不同阶段
- C语言深度解剖——读书笔记-3、关键字(const、 volatile、extern、struct、union、enum、typedef)
- 用图像的块的极大值对图像进行处理
- 判断单链表是否有环
- POJ3253Fence Repair【贪心+优先队列 】
- nyoj 48小明的调查作业
- 编程之美:第四章 数字之趣 4.1金刚坐飞机问题