首页 > 代码库 > C++复数运算符重载(+与<<)
C++复数运算符重载(+与<<)
Description
定义一个复数类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;
};
//将程序需要的其他成份写在下面,只提交begin到end部分的代码
//******************** begin ********************
//********************* end ********************
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;
}
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)
HINT
只提交自己定义的函数部分,控制输出小数点后两位,用 setiosflags(ios::fixed);和setprecision(2);控制
1 #include <iostream> 2 #include <iomanip> 3 using namespace std; 4 5 class Complex 6 { 7 public: 8 Complex():real(0),imag(0) {} 9 Complex(double r,double i):real(r),imag(i) {} 10 Complex operator+(Complex &); 11 Complex operator+(double &); 12 friend Complex operator+(double&,Complex &); 13 friend ostream& operator << (ostream& output, const Complex& c); 14 private: 15 double real; 16 double imag; 17 }; 18 19 //将程序需要的其他成份写在下面,只提交begin到end部分的代码 20 //******************** begin ******************** 21 Complex Complex::operator+(Complex &c1) 22 {return(Complex(real+c1.real,imag+c1.imag));} 23 Complex Complex::operator+(double &d1) 24 {return(Complex(real+d1,imag));} 25 Complex operator+(double&d1,Complex &c1) 26 {return(Complex(d1+c1.real,c1.imag));} 27 ostream& operator << (ostream& output, const Complex& c) 28 { 29 if(c.imag>0) 30 output<<setiosflags(ios::fixed)<<setprecision(2)<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl; 31 else 32 output<<setiosflags(ios::fixed)<<setprecision(2)<<"("<<c.real<<c.imag<<"i)"<<endl; 33 return output; 34 } 35 36 //********************* end ******************** 37 int main() 38 { 39 //测试复数加复数 40 double real,imag; 41 cin>>real>>imag; 42 Complex c1(real,imag); 43 cin>>real>>imag; 44 Complex c2(real,imag); 45 Complex c3=c1+c2; 46 cout<<"c1+c2="; 47 cout<<c3; 48 49 //测试复数加实数 50 double d; 51 cin>>real>>imag; 52 cin>>d; 53 c3=Complex(real,imag)+d; 54 cout<<"c1+d="; 55 cout<<c3; 56 57 //测试实数加复数 58 cin>>d; 59 cin>>real>>imag; 60 c1=Complex(real,imag); 61 c3=d+c1; 62 cout<<"d+c1="; 63 cout<<c3; 64 65 return 0; 66 }