假定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;
}