输入输出流的重载及类型转换运算符的重载

通过重载输入,输出流,实现复数的流输入,类型转换的重载:

#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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值