复数类中运算符重载的改造

/*
* 程序的版权和版本声明部分
* Copyright (c)2014, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称:a.cpp
* 作    者:孔云
* 完成日期:2014年4月22日
* 版 本 号: v1.0
* 输入描述:主函数中给出。
* 问题描述:用类成员函数定义复数类重载运算符,进行复数加减乘除运算,再定义一目运算符“-”和Complex类中的重载流插入运算符<<,实现运算结果输出。
* 输出描述:各种运算结果。
*/
#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);
    friend ostream&operator<<(ostream&,Complex&);
    Complex operator-();
private:
    double real;
    double imag;
};
//下面定义成员函数
//复数的四则运算
Complex Complex::operator+(Complex &c2)
{
    Complex a;
    a.real=real+c2.real;
    a.imag=imag+c2.imag;
    return a;
}
Complex Complex::operator-(Complex &c2)
{
    Complex b;
    b.real=real-c2.real;
    b.imag=imag-c2.imag;
    return b;
}
Complex Complex::operator*(Complex &c2)
{
    Complex c;
    c.real=real*c2.real-imag*c2.imag;
    c.imag=imag*c2.real+real*c2.imag;
    return c;
}
Complex Complex::operator/(Complex &c2)
{
    int k=c2.real*c2.real+c2.imag*c2.imag;
    Complex d;
    d.real=(real*c2.real+imag*c2.imag)/k;
    d.imag=(imag*c2.real+real*c2.imag)/k;
    return d;
}
//重载流插入运算符
ostream&operator<<(ostream& output,Complex&c)
{
    if(c.imag<0)
    {
        output<<"("<<c.real<<c.imag<<"i)"<<endl;
    }
    else
    {
        output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
    }
    return output;
}
//定义一目运算符
Complex Complex::operator-()
{
    Complex f;
    f.real=0-real;
    f.imag=0-imag;
    return f;
}
//下面定义用于测试的main()函数
int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    cout<<"c1=";
    cout<<c1;
    cout<<"c2=";
    cout<<c2;
    c3=c1+c2;
    cout<<"c1+c2=";
    cout<<c3;
    c3=c1-c2;
    cout<<"c1-c2=";
    cout<<c3;
    c3=c1*c2;
    cout<<"c1*c2=";
    cout<<c3;
    c3=c1/c2;
    cout<<"c1/c2=";
    cout<<c3;
    c3=-c1;
    cout<<"-c1=";
    cout<<c3;
    c3=-c2;
    cout<<"-c2=";
    cout<<c3;
    return 0;
}


复数类中运算符重载的改造_第1张图片

心得体会:此程序在上周博文基础上做,非常容易,在这里想提一提的是重载流插入运算符<<,小小一个流插入运算符,只不过输出程序结果,竟然也有运算符重载,可见C++中的各个角色不一般啊!奋斗

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