使用运算符重载实现复数的四则运算

来源:互联网 发布:vasp软件安装 编辑:程序博客网 时间:2024/05/15 23:52

程序代码:

#include <iostream>using namespace std;class Complex   {public:      Complex( )//定义默认构造函数初始化复数      {          real=0;          imag=0;      }                 //使用初始化表初始化复数      Complex(double r, double i):real(r),imag(i){}           Complex operator+(Complex &c2);//复数的加法      Complex operator-(Complex &c2);//复数的减法      Complex operator*(Complex &c2);//复数的乘法      Complex operator/(Complex &c2);//复数的除法      void display( );//显示复数private:      double real;//复数的实部      double imag;//复数的虚部};//复数的加法Complex Complex::operator+(Complex &c2){    Complex c3;    c3.real  = real + c2.real;    c3.imag  = imag + c2.imag;    return c3;}//复数的减法Complex Complex::operator-(Complex &c2){    Complex c3;    c3.real  = real - c2.real;    c3.imag  = imag - c2.imag;    return c3;}//复数的乘法Complex Complex::operator*(Complex &c2){    Complex c3;    c3.real = real*c2.real - imag * c2.imag;    c3.imag = real*c2.imag + imag * c2.real;    return c3;}//复数的除法Complex Complex::operator/(Complex &c2){      Complex c3;    c3.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);    c3.imag = (imag * c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);    return c3;}//显示复数void Complex::display( ){    cout<<real<<'+'<<imag<<'i'<<endl;}int main( ){    //定义三个复数    Complex c1(8,10), c2(7,2), c3;    //打印第一个复数    cout<<"c1 = ";    c1.display();       //打印第二个复数    cout<<"c2 = ";    c2.display();    //两个复数相加    c3 = c1 + c2;    cout<<"c1 + c2 = ";    c3.display();    //两个复数想减    c3 = c1 - c2;    cout<<"c1 - c2 = ";    c3.display();    //两个复数相乘    c3 = c1 * c2;    cout<<"c1 * c2 = ";    c3.display();    //两个复数相除    c3 = c1 / c2;    cout<<"c1 / c2 = ";    c3.display();    system("pause");}


执行结果:


1 1
原创粉丝点击