输出流为常量就不能使用输出操作符?

haow85 2010-09-28 12:21:36
请看下面的代码:

#include <iostream>
#include <sstream>
using namespace std;

int main (int argc, char * const argv[]) {

stringstream os;
os << 5 << endl;

const stringstream os1; // 实践出真知:输出流为常量就不能使用输出操作符
os1 << 6 << endl;

return 0;
}

...全文
118 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2010-09-28
  • 打赏
  • 举报
回复
一个流对像类型里面会有缓冲区指针,流状态,掩码等信息,你这里这样输入的话,缓冲区里面的内容肯定有变化(这个可能不成为问题)。流状态也有可能被改变。而且<<肯定涉及到里面一些非const成员函数的调用。从来没看过流对象用const修饰。
hastings 2010-09-28
  • 打赏
  • 举报
回复
ostream::operator<< public member function 
ostream& operator<< (bool& val );
ostream& operator<< (short& val );
ostream& operator<< (unsigned short& val );
ostream& operator<< (int& val );
ostream& operator<< (unsigned int& val );
ostream& operator<< (long& val );
ostream& operator<< (unsigned long& val );
ostream& operator<< (float& val );
ostream& operator<< (double& val );
ostream& operator<< (long double& val );
ostream& operator<< (void*& val );

ostream& operator<< (streambuf& sb );

ostream& operator<< (ostream& ( *pf )(ostream&));
ostream& operator<< (ios& ( *pf )(ios&));
ostream& operator<< (ios_base& ( *pf )(ios_base&));

*** the following functions are not members but GLOBAL functions:

ostream& operator<< (ostream& out, char c );
ostream& operator<< (ostream& out, signed char c );
ostream& operator<< (ostream& out, unsigned char c );

ostream& operator<< (ostream& out, const char* s );
ostream& operator<< (ostream& out, const signed char* s );
ostream& operator<< (ostream& out, const unsigned char* s );

没有一个是const的。。
haow85 2010-09-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 cheeralen 的回复:]

为什么要去改变一个常量?
[/Quote]
<< 改变输出流对象?输出流到底咋实现的?
暗黑帝国 2010-09-28
  • 打赏
  • 举报
回复
为什么要去改变一个常量?
haow85 2010-09-28
  • 打赏
  • 举报
回复
我其实是想知道到底怎么回事
  • 打赏
  • 举报
回复
顶一个...楼主给点分,升星
haow85 2010-09-28
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 pengzhixi 的回复:]

一个流对像类型里面会有缓冲区指针,流状态,掩码等信息,你这里这样输入的话,缓冲区里面的内容肯定有变化(这个可能不成为问题)。流状态也有可能被改变。而且<<肯定涉及到里面一些非const成员函数的调用。从来没看过流对象用const修饰。
[/Quote]
明白了。

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧