通过重载输入,输出流,实现复数的流输入,类型转换的重载:
#include<bits/stdc++.h>
using namespace std;
class Complex{
double real,imag;
public:
Complex(double r=0,double i=0):real(r),imag(i) {}
friend ostream & operator<<(ostream & os,const Complex & c); //友元调用私有成员
friend istream & operator>>(istream & is,Complex & c);
operator double(){//重载double使其将类转换成double; 不需要写返回类型double
return real;
}
};
ostream & operator<<(ostream & os,const Complex & c){//输出流重载
os<<c.real<<"+"<<c.imag<<"i"<<endl;
return os;
}
istream & operator>>(istream & is,Complex & c){//输入流重载
string s;
is>>s;
int pos=s.find("+",0);//查找“+”的位置;
string sr=s.substr(0,pos);//分离实部的字符串
c.real=atof(sr.c_str()); //atof库函数将const char*指针指向的内容转换成float
sr=s.substr(pos+1,s.length()-pos-2);//分离虚部字符串
c.imag=atof(sr.c_str());
return is;
}
int main(){
Complex c,d;
int n;
cin>>c>>d>>n;
cout<<c<<d<<n;
cout<<endl<<(double)c * (double)d;
double m=8+c+d; //等价于m=8+(double)c+(double)d
cout<<endl<<m;
return 0;
}
结果:
6+8i
5+4i
9
6+8i
5+4i
9
30
19