cout << string是怎么实现的?

legend-never-die 2004-04-12 04:27:29
这个<<是谁去重载呀?是cout还是string?

注:此处的string是标准库的string
...全文
338 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
薛定谔之死猫 2004-04-15
  • 打赏
  • 举报
回复
看汇编代码罗,后者重载是见过滴
fvv 2004-04-14
  • 打赏
  • 举报
回复
WinMain 及窗口回调 是全局函数吗,它怎么被封装的。看深入浅出的 大挪移
legend-never-die 2004-04-14
  • 打赏
  • 举报
回复
TO:FVV

我也看见了,应该是由string来重载,可是重载operator << 需要写成全局函数呀,难道string类里面也是写成全局函数吗?
fvv 2004-04-13
  • 打赏
  • 举报
回复
写个简单的重载函数实现的例子(不一定是和C++定义的那样)只是举例.
ostream& operator<<(ostream cout,string &str)
{
for(int i=0;i<str.lenght()+1;i++)
cout<<str[i]; //operator[]也重载过
return cout;
}
fvv 2004-04-13
  • 打赏
  • 举报
回复
由string来重载.msdn的描述.
Illustrates how to use the string::operator<< Standard Template Library (STL) function in Visual C++.

template<class _E, class _TYPE, class _A> inline
basic_ostream<_E, _TYPE>&operator<<( basic_ostream<_E, _TYPE>& OStream,
const basic_string<_E, _TYPE, _A>& XString);

Note The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.
Remarks
The operator<< is used to insert a string into an output stream.
Example
// StringInsertion.cpp
// compile with: /EHsc
// Illustrates how to use the insertion operator
// (operator<<) to insert a string into an output
// stream.
//
// Functions:
//
// operator<< Inserts a string into an output stream.
//////////////////////////////////////////////////////////////////////

#pragma warning(disable:4786)
#include <string>
#include <iostream>

using namespace std ;

int main()
{
string msg="Hello! This is the insertion operator.";
cout << msg << endl;
}
Output
Hello! This is the insertion operator.
legend-never-die 2004-04-12
  • 打赏
  • 举报
回复
ding~~~~~~
legend-never-die 2004-04-12
  • 打赏
  • 举报
回复
to: mahatma_cn(鱼和胸罩不可兼得)

这个全局函数怎么由别人去用呀,弄点伪代码来瞧瞧

to:sgnaw(李逍遥)
怎么说到关键的地方就不说了?按我的理解来说,<<都应该由要输出的类来重载,并且要做为全局函数来重载,可是我就奇了怪了,没见到string有重载<<的代码。。。
王国凡 2004-04-12
  • 打赏
  • 举报
回复
Q: 可是cout怎么知道怎么输出object中的成员变量的值呢?

A: cout 的确不知道,但 << 知道,可能你还会问,为什么 << 知道,:-) 看来你的所有疑问只有 Bjarne Stroustrup 来解答了,看他的书《The C++ Programming Language》关于 bitset 和 cout 的相关部分。
zhujianping_es 2004-04-12
  • 打赏
  • 举报
回复
<< is overriden by "cout" function!
Not the string !!
mahatma_cn 2004-04-12
  • 打赏
  • 举报
回复
应该由string的实作者重载<<,但是<<操作符号不是string类成员,是全局函数
zcchm 2004-04-12
  • 打赏
  • 举报
回复
需要你重载<<
legend-never-die 2004-04-12
  • 打赏
  • 举报
回复
嗯,谢谢

可是cout怎么知道怎么输出object中的成员变量的值呢?
王国凡 2004-04-12
  • 打赏
  • 举报
回复
应该是 cout , cout << object

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

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