用成员运算符重载函数进行复数运算

来源:互联网 发布:美工使用的软件 编辑:程序博客网 时间:2024/05/17 16:43
#include<iostream>using namespace std;class Complex  //声明复数类Complex{public:Complex(double r=0.0,double i=0.0);//声明构造函数void display();//显示输出复数Complex operator+(Complex& c);//声明用成员函数重载运算符“+”    Complex operator-(Complex& c);//声明用成员函数重载运算符“-”    Complex operator*(Complex& c);//声明用成员函数重载运算符“*”    Complex operator/Complex& c);//声明用成员函数重载运算符“/”private:double real;//复数的实数部分double imag;//复数的虚数部分};Complex::Complex(double r,double i)//定义构造函数{real=r;imag=i;}Complex Complex::operator+(Complex& c)//重载运算符“+”的实现{Complex temp;temp.real=real+c.real;temp.imag=imag+c.imag;return temp;}Complex Complex::operator-(Complex& c)//重载运算符“-”的实现{Complex temp;temp.real=real-c.real;temp.imag=imag-c.imag;return temp;}Complex Complex::operator*(Complex& c)//重载运算符“*”的实现{Complex temp;temp.real=real*c.real-imag*c.imag;temp.imag=real*c.imag+imag*c.real;return temp;}Complex Complex::operator/(Complex& c)//重载运算符“/”的实现{Complex temp;double t;t=1/(c.real*c.real+c.imag*c.imag);temp.real=(real*c.real+imag*c.imag)*t;temp.imag=(c.real*imag-real*c.imag)*t;return temp;}void Complex::display()//显示复数的实数部分和虚数部分{cout<<real;if(imag>0){cout<<"+";}if(imag!=0){cout<<imag<<"i\n";}}int main(){Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4,A5,A6;//定义六个复数类对象A3=A1+A2;A4=A1-A2;A5=A1*A2;A6=A1/A2;A1.display();        A2.display();        A3.display();        A4.display();        A5.display();        A6.display();return 0;}

0 0
原创粉丝点击