有关cin和cout的重构问题

假定c是Complex复数类的对象,现在希望 写“cout << c;”,就能以“a+bi”的形式输出c的值,写“cin>>c;”,就能从键 盘接受“a+bi”形式的输入,并且使得 c.real = a,c.imag = b。
一般来说,对于初学的话,最好的写法就是以下的写法,那些只输出一个<<的比较难以实现,而且对于iostream的成员函数不能随意更改,能更改的就像我写的这种,定义为全局函数,这样比较稳妥,对于返回值,其实可以理解成从左往右,每次处理一个,cin和cout继续往右边走
#include<iostream>
#include<string.h>
using namespace std;
class math{
	private:
		double shi,xu;
	public:
		math(double x=0,double y=0):shi(x),xu(y){}
		friend ostream& operator<<(ostream& a,const math& b);
		friend istream& operator>>(istream& a,math& b);
};
ostream& operator<<(ostream& a,const math& b)
{
	a<<b.shi<<"+"<<b.xu<<"i"<<" ";
	return a;
}
istream& operator>>(istream& a,math& b)
{
	string c;
	a>>c;
	int pos=c.find('+',0);
	string q=c.substr(0,pos);
	b.shi=stoi(q.substr());
	q=c.substr(pos+1,c.size()-pos-2);
	b.xu=stoi(q.substr());
	return a;
}
int main()
{
	math A;
	int n;
	cin>>A>>n;
	cout<<A<<n;
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值