string也可以用 <<和>>吗?

972 篇文章 329 订阅
73 篇文章 32 订阅

       最近在项目工程中碰到一段代码, 颇为费解, string居然也可以用 <<和>>, 于是我单独写了个小程序测了一下:

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


int main()
{
	int a = 1;
	string s;
	s << a;

	return 0;
}
     编译错误:error: no match for 'operator<<' in 's << a'   这是正常的。 

     但为什么在工程项目中就可以呢? 请教了一下别的同事, 才发现, 是对string进行了扩展, 在项目工程中写测试代码, 部分代码如下:

// 工程中的部分代码
int main()
{
	int a = 1;
	float b = 2.0f;
	bool c = true;
	string d = "hello world";
	
	string s;
	s << a;
	s << b;
	s << c;
	s << d;

	cout << "size is " << s.size() << endl;

	int a2;
	float b2;
	bool c2;
	string d2;
	s >> a2;
	s >> b2;
	s >> c2;
	s >> d2;

	cout << a2 << endl;
	cout << b2 << endl;	
	cout << c2 << endl;
	cout << d2 << endl;

	cout << "size is " << s.size() << endl;
	
	return 0;
}
     结果为:

size is 22
1
2
1
hello world
size is 0

     

     可见, string在这里具备了类似流的功能。






  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值