关于ostringstream的.operator<<()出错问题

jacky_qiu 2010-11-30 07:27:45


#include<iostream>
#include <Windows.h>
#include <sstream>
#include <tchar.h>
#include <string>
using namespace std;

void main()
{
//这样得到的结果是错误的。
//输出的是一个地址,而不是字符串
ostringstream test;
test.operator<<("this is a test string");
cout<<( std::string(test.str()).c_str() )<<endl;

//这样就正确
ostringstream test2;
test2<<("this is a test string");
cout<<( std::string(test2.str()).c_str() )<<endl;
/*

//想请问为什么直接使用<< 和 使用 .operator<<() 会得到
//不同的结果,因为我想继承ostringstream重载<<
//必须调用基类的ostringstream::operator<<()方法
但结果却出错了。希望大家给点意见,谢谢!


class Newstringstream : public std::ostringstream
{
public:
ostringstream& operator << (POINT &point)
{
//这里出错了
ostringstream::operator<<
(_T("("))<<(point.x)<<(_T(","))<<(point.y)<<(_T(")"));
return *this;
}
};

*/

}



...全文
184 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dubiousway 2010-11-30
  • 打赏
  • 举报
回复
改成这样就ok:

ostringstream test;
operator<<(test,"this is a test string");
cout<<( std::string(test.str()).c_str() )<<endl;


我查了一下,和字符串输出相关的重载operator<<,都是两个参数的全局函数,而不是成员函数。
所以如果你输入一个参数(当成员函数来调用,那么就只能被当作字符串地址输出了)

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<< (const 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 );
libinfei8848 2010-11-30
  • 打赏
  • 举报
回复
重载operator<<方法最好不要做成员函数,做friend。或者全局函数

ostringstream& operator << (Newstringstream &, POINT &point)
jacky_qiu 2010-11-30
  • 打赏
  • 举报
回复
谢谢两位!

64,647

社区成员

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

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