继承ostringstream的一个问题

pig4210 2009-12-07 03:49:17


class dbgout:public ostringstream
{
public:


dbgout& __CLR_OR_THIS_CALL operator<< (dbgout& (__cdecl *_Pfn)(dbgout&))
{
_DEBUG_POINTER(_Pfn);
return ((*_Pfn)(*this));
}
protected:
private:
};


namespace std{
dbgout& __cdecl endd(dbgout& _Ostr)
{
OutputDebugStringA(_Ostr.str().c_str());
return _Ostr;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
dbgout dd;

dd<<"------"<<endl<<endd;
cout<<dd.str();
return 0;
}



如上,意思很明确,想做一个函数endd,调用使OuputDebugString输出。编译成功,运行结果:

------
00401000

情况:一:多余输出了endd函数的地址。二:并没有调用OuputDebugString。
那么,应该怎么写。请赐教,谢谢!
...全文
251 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
pig4210 2009-12-10
  • 打赏
  • 举报
回复
算了,用笨办法解决了
pig4210 2009-12-10
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 taodm 的回复:]
去图书馆找本《标准C++输入输出流与本地化》,这书恐怕已经没法买到了。
[/Quote]
今天找到这本书,看了一下,有一章讲用户自定义操纵符。看过后有所领悟。写如下代码:

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


template<class _Elem,
class _Traits> inline
basic_ostream<_Elem, _Traits>&
__CLRCALL_OR_CDECL endd(basic_ostream<_Elem, _Traits>& _Ostr)
{ // insert newline and flush stream
ostringstream& oo = (ostringstream&)_Ostr;
OutputDebugStringA(oo.str().c_str());
oo.str("");
return (_Ostr);
}


int _tmain(int argc, _TCHAR* argv[])
{
ostringstream dout;
dout<<"this is "<<endd;
cout<<"ok"<<endl;
return 0;
}




成功实现预期功能。再想一想,曾经离成功很近很近。但是还是读书少哇,怎么就看不透一层窗户纸。
书中自有黄金屋,古人诚不我欺!
taodm 2009-12-08
  • 打赏
  • 举报
回复
去图书馆找本《标准C++输入输出流与本地化》,这书恐怕已经没法买到了。
[Quote=引用 6 楼 pig4210 的回复:]
不能继承么???那么对ostringstream新加一个endd这么一个函数如何添加?
[/Quote]
linglongyouzhi 2009-12-08
  • 打赏
  • 举报
回复
用Decorator 模式扩展
pig4210 2009-12-08
  • 打赏
  • 举报
回复
不能继承么???那么对ostringstream新加一个endd这么一个函数如何添加?
冻结 2009-12-07
  • 打赏
  • 举报
回复
STL的类为了效率,都是不愿意被继承的。
chuengchuenghq 2009-12-07
  • 打赏
  • 举报
回复
up
老邓 2009-12-07
  • 打赏
  • 举报
回复
我猜测原因是:operator<<已经被重载了。
由于重载是static函数,所以,你没有办法改写它 ?
老邓 2009-12-07
  • 打赏
  • 举报
回复
你的重载是失败的。
#include <iostream>
#include <sstream>
#include <string>


namespace std
{

class dbgout : public ostringstream
{
public:

dbgout& __CLR_OR_THIS_CALL operator<<(dbgout& (__cdecl *_Pfn)(dbgout&))
{
cout << "test" << endl; // 根本没进来啊
_DEBUG_POINTER(_Pfn);
return ((*_Pfn)(*this));
}
protected:
private:
};


dbgout& __cdecl endd(dbgout& _Ostr)
{
cout << "test" << _Ostr.str() << endl;
OutputDebugStringA(_Ostr.str().c_str());
return _Ostr;
}
}


using namespace std;

int main()
{
dbgout dd;

dd << "------" << endl << endd;
cout << dd.str();
return 0;
}

根本没打印出test
taodm 2009-12-07
  • 打赏
  • 举报
回复
呃,没事别从ostram继承,那玩意儿没设计为可以让你安全继承。
最多可以对它用“委托”

64,642

社区成员

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

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