第八周--项目一 实现复数类中的运算符重载(2)

  1. /* 
  2. * 烟台大学未来工程师协会/CSDN俱乐部 算法达人修炼营 实践报告 
  3. * Copyright (c) 2011, 烟台大学计算机学院学生  
  4. * All rights reserved. 
  5. * 作    者:      牛建伟                         
  6. * 完成日期:    2014     年  4   月  15   日 
  7. * 版 本 号:           vo.1
  8. * 任务描述:用类的友元函数,而不是成员函数,完成重载运算符+、-、*、/,使之能用于复数的加减乘除;
  9. 样例输入:
  10. 样例输出:
  11. 问题分析:
  12. /*
    #include<iostream>
    #include<cstring>
    using namespace std;
    class Complex
    {
    public:
        Complex()
        {
            real=0;
            imag=0;
        }
        Complex(double r,double i)
        {
            real=r;
            imag=i;
        }
        friend Complex operator+(Complex &c2,Complex &c3);
        friend Complex operator-(Complex &c2,Complex &c3);
        friend Complex operator*(Complex &c2,Complex &c3);
        friend Complex operator/(Complex &c2,Complex &c3);
        friend void display(Complex&c);
    private:
        double real;
        double imag;
    };
    Complex operator+(Complex &c2,Complex &c3)
    {
        Complex c;
        c.real=c2.real+c3.real;
        c.imag=c2.imag+c3.imag;
        return c;
    }
    Complex operator-(Complex &c2,Complex &c3)
    {
        Complex c;
        c.real=c2.real-c3.real;
        c.imag=c2.imag-c3.imag;
        return c;
    }
    Complex operator*(Complex &c2,Complex &c3)
    {
        Complex c;
        c.real=c2.real*c3.real-c2.imag*c3.imag;
        c.imag=c2.imag*c3.real+c2.real*c3.imag;
        return c;
    }
    Complex operator/(Complex &c2,Complex &c3)
    {
        Complex c;
        double d=c3.real*c3.real+c3.imag*c3.imag;
        c.real=(c2.real*c3.real+c2.imag*c3.imag)/d;
        c.imag=(c2.imag*c3.real-c2.real*c3.imag)/d;
        return c;
    }
    void display(Complex&c)
    {
        cout<<c.real<<"+"<<c.imag<<"i"<<endl;
    }
    //下面定义用于测试的main()函数
    int main()
    {
        Complex c1(3,4),c2(5,-10),c3;
        cout<<"c1=";
        display(c1);
        cout<<"c2=";
        display(c2);
        c3=c1+c2;
        cout<<"c1+c2=";
        display(c3);
        c3=c1-c2;
        cout<<"c1-c2=";
        display(c3);
        c3=c1*c2;
        cout<<"c1*c2=";
        display(c3);
        c3=c1/c2;
        cout<<"c1/c2=";
        display(c3);
        return 0;
    }
    

  13. /*操作结果:第八周--项目一 实现复数类中的运算符重载(2)_第1张图片
  14. 心得体会:照着葫芦画瓢...感觉还行吧。。

你可能感兴趣的:(第八周--项目一 实现复数类中的运算符重载(2))