第十二周上机实践项目-项目1-3-实现复数类中的运算符重载

/*copyright(c)2016.烟台大学计算机学院
 * All rights reserved,
 * 文件名称:text.Cpp
 * 作者:刘涛
 * 完成日期:2016年5月12日
 * 版本号:vc++6.0
 *问题描述:请用类的成员函数,定义复数类重载运算符+、-、*、/,使之能用于复数的加减乘除
 定义一个定义完整的类(是可以当作独立的产品发布,成为众多项目中的“基础工程”)。这样的类
 在(2)的基础上,扩展+、-、*、/运算符的功能,使之能与double型数据进行运算。设Complex c; 
 double d; c+d和d+c的结果为“将d视为实部为d的复数同c相加”,其他-、*、/运算符类似。
 */
 #include<iostream>
 using namespace std;
 class Complex
{
public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i){real=r; imag=i;}
    friend Complex operator+(const Complex &c1,const Complex &c2);
    friend Complex operator-(const Complex &c1,const Complex &c2);
    friend Complex operator*(const Complex &c1,const Complex &c2);
    friend Complex operator/(const Complex &c1,const Complex &c2);


    friend Complex operator+(const Complex &c1,double &d);
    friend Complex operator-(const Complex &c1,double &d);
    friend Complex operator*(const Complex &c1,double &d);
    friend Complex operator/(const Complex &c1,double &d);
    void display();
private:
    double real;
    double imag;
};
//下面定义成员函数
Complex operator+(const Complex &c1,const Complex &c2)
{
    return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex operator-(const Complex &c1,const Complex &c2)
{
    return Complex(c1.real-c2.real,c1.imag-c2.imag);
}
Complex operator*(const Complex &c1,const Complex &c2)
{
    return Complex(c1.real*c2.real,c1.imag*c2.imag);
}
Complex operator/(const Complex &c1,const Complex &c2)
{
    return Complex(c1.real/c2.real,c1.imag/c2.imag);
}

/*----------------------------------------------------------------*/
Complex operator+(const Complex &c1,double &d)
{
    return Complex(c1.real+d,c1.imag);
}
Complex operator-(const Complex &c1,double &d)
{
    return Complex(c1.real-d,c1.imag);
}
Complex operator*(const Complex &c1,double &d)
{
    return Complex(c1.real*d,c1.imag);
}
Complex operator/(const Complex &c1,double &d)
{
    return Complex(c1.real/d,c1.imag);
}
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<")"<<endl;
}

int main()
{
    Complex c1(3,4),c2(5,-10),c3,c4;
    double d(2.32);
    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();
    cout<<"****************"<<endl;


    c4=c1+d;
    cout<<"c1+d=";
    c4.display();
    c4=c1-d;
    cout<<"c1-d=";
    c4.display();
    c4=c1*d;
    cout<<"c1*d=";
    c4.display();
    c4=c1/d;
    cout<<"c1/d=";
    c4.display();
    return 0;
}
运行结果:
<img src="http://img.blog.csdn.net/20160512191940999?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
知识点总结:一个复数和一个实数的加减乘除。
学习心得:c+d的意义和d+c的意义不一样,定义的时候也要注意这个问题,需要特别关注的是当实数载前面的时候,只能采用非成员函数来实现,不能使用成员函数。

你可能感兴趣的:(实现复数类中的运算符重载)