重载运算符+

来源:互联网 发布:方维社区o2o系统 源码 编辑:程序博客网 时间:2024/06/10 17:41
/** Copyright (c) 2013 烟台大学计算机与控制工程学院* All rights reserved* 作    者: 刘慧艳* 完成日期:2014 年6月20日* 版 本 号:v1.0* 问题描述:定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算与输出操作。(1)参加运算的两个运算量可以都是类对象,也可以其中有一个是实数,顺序任意。例如,c1+c2,d+c1,c1+d均合法(设d为实数,c1,c2为复数)。(2)输出的算数,在复数两端加上括号,实部和虚部均保留两位小数,如(8.23+2.00i)、(7.45-3.40i)、(-3.25+4.13i)等。编写程序,分别求两个复数之和、整数和复数之和,并且输出。请在下面的程序段基础上完成设计:*/#include <iostream>#include <iomanip>using namespace std;class Complex{public:    Complex():real(0),imag(0) {}    Complex(double r,double i):real(r),imag(i) {}    Complex operator+(Complex &);    Complex operator+(double &);    friend Complex operator+(double&,Complex &);    friend ostream& operator << (ostream& output, const Complex& c);private:    double real;    double imag;};Complex Complex::operator+(Complex &c){    return  Complex(c.real+real,c.imag+imag);}Complex Complex::operator+(double &c){    return  Complex(c+real,imag);}Complex operator+(double&c1,Complex &c2){    return  Complex(c2.real+c1,c2.imag);}ostream& operator << (ostream& output, const Complex& c){    cout<<setiosflags(ios::fixed)<<setprecision(2);    output<<"("<<c.real;    if(c.imag>0)    {        cout<<"+";    }    else{}    cout<<c.imag<<"i)"<<endl;    return output;}int main(){    //测试复数加复数    double real,imag;    cin>>real>>imag;    Complex c1(real,imag);    cin>>real>>imag;    Complex c2(real,imag);    Complex c3=c1+c2;    cout<<"c1+c2=";    cout<<c3;    //测试复数加实数    double d;    cin>>real>>imag;    cin>>d;    c3=Complex(real,imag)+d;    cout<<"c1+d=";    cout<<c3;    //测试实数加复数    cin>>d;    cin>>real>>imag;    c1=Complex(real,imag);    c3=d+c1;    cout<<"d+c1=";    cout<<c3;    return 0;}

0 0
原创粉丝点击