定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算与输出操作。 (1)参加运算的两个运算量可以都是类对象,也可以其中有一个是实数,顺序任意。例如,c1+c2,d+c1,c1+d均合法(设d为实数,c1,c2为复数)。 (2)输出的算数,在复数两端加上括号,实部和虚部均保留两位小数,如(8.23+2.00i)、(7.45-3.40i)、(-3.25+4.13i)等。 编写程序,分别求两个复数之和、整数和复数之和,并且输出。
} Input 一个复数的实部和虚部,另一个复数的实部和虚部 一个复数的实部和虚部,一个实数 一个实数,一个复数的实部和虚部 Output 两个复数之和、复数和实数之和,实数和复数之和。 Sample Input 3 4 5 -10 3 4 5 5 3 4 Sample Output c1+c2=(8.00-6.00i) c1+d=(8.00+4.00i) d+c1=(8.00+4.00i)
#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 &,const Complex &c); private: double real; double imag; }; Complex Complex::operator+(Complex &c) {return Complex(real+c.real,imag+c.imag);} Complex Complex::operator+(double &r) {return Complex(real+r,imag);} Complex operator+(double &r,Complex&c) {return Complex(r+c.real,c.imag);} ostream& operator<<(ostream &cout,const Complex &c) { cout<<setiosflags(ios::fixed); cout<<setprecision(2);cout<<'('<<c.real; if(c.imag>0) cout<<'+'; cout<<c.imag<<"i)"<<endl; } 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; }