输入输出运算符重载


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

//输入输出流运算符重载有两点需要注意
//1. 函数参数要用引用,primer上是这样解释的:不用引用的话就是按值传递,而iostream规定是不允许拷贝其副本的,所以必须要用引用
//2. 函数返回值应当是函数参数中输入输出流的引用,这是为了适用于连续输入输出的情形,具体见下面的例子
//参考 http://blog.sina.com.cn/s/blog_731b2f5b01018byp.html
struct MyStruct
{
  int a;
  int b;
  MyStruct(): a(0), b(0){}
};

//适用于情形1和情形2
istringstream &operator>>(istringstream &in, MyStruct &t) {
  in >> t.a;
  in >> t.b;
  return in;
}

//只适用于情形1
//void operator>>(istringstream &in, MyStruct &t) {
//  in >> t.a;
//  in >> t.b;
//}

int main()
{
  MyStruct t1, t2;

  //情形1
  //const string& arg = "1 2 3 4";
  //istringstream arg_ss (arg, istringstream::in);
  //arg_ss >> t1;
  //arg_ss >> t2;

  //情形2:连续读入
  const string& arg = "1 2 3 4";
  istringstream arg_ss (arg, istringstream::in);
  arg_ss >> t1 >> t2;

  int ttt = 0;
  return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值