8_1_3

来源:互联网 发布:阿里云 gb2312 编辑:程序博客网 时间:2024/05/01 09:35
#include <iostream>class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}friend Complex operator+(double d,Complex &b);friend Complex operator-(double d,Complex &b);friend Complex operator*(double d,Complex &b);friend Complex operator/(double d,Complex &b);friend Complex operator+(Complex &b,double d);friend Complex operator-(Complex &b,double d);friend Complex operator*(Complex &b,double d);friend Complex operator/(Complex &b,double d);void display();private:double real;double imag;};//下面定义成员函数Complex operator+(double d,Complex &b){Complex c;c.real=d+b.real;c.imag=b.imag;return c;}Complex operator-(double d,Complex &b){Complex c;c.real=b.real-d;c.imag=b.imag;return c;}Complex operator*(double d,Complex &b){Complex c;c.real=b.real*d-b.imag*0;c.imag=b.imag*d+b.real*0;return c;}Complex operator/(double d,Complex &b){Complex c;double m;m=b.real*b.real+0*0;c.real=(b.real*d+b.imag*d)/m;c.imag=(b.imag*d-b.real*0)/m;return c;}void Complex::display(){std::cout<<real<<","<<imag<<"i"<<std::endl; }Complex operator+(Complex &b,double d){Complex c;c.real=d+b.real;c.imag=b.imag;return c;}Complex operator-(Complex &b,double d){Complex c;c.real=b.real-d;c.imag=b.imag;return c;}Complex operator/(Complex &b,double d){Complex c;double m;m=b.real*b.real+b.imag*b.imag;c.real=(d*d+0*b.imag)/m;c.imag=(0*b.real-d*b.imag)/m;return c;}//下面是测试函数int main(){double c1=3;Complex c2(5,-10),c3,c4;std::cout<<"c1="<<c1;std::cout<<"c2=";c2.display();c3=c1+c2;std::cout<<"c1+c2=";c3.display();c3=c1-c2;std::cout<<"c1-c2=";c3.display();c3=c1*c2;std::cout<<"c1*c2=";c3.display();c3=c1/c2;c4=c2/c1;std::cout<<"c1/c2=";c3.display();std::cout<<"c2/c1=";c4.display();return 0;}