码迷,mamicode.com
首页 > 其他好文 > 详细

第九周(运算符重载复数类)

时间:2015-05-13 10:39:48      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:c++ 生活

/*
*copyright(c) 2015,烟台大学计算机学院
*All rights reserved。
*文件名称:第九周(运算符重载)

*作者:王忠
*完成日期:2015.5.13

*版本号: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+(const Complex &c2);
    Complex operator-(const Complex &c2);
    Complex operator*(const Complex &c2);
    Complex operator/(const Complex &c2);
    friend Complex operator-(Complex &c2);
    void display();
    friend ostream& operator <<(ostream& output,const Complex& c);
    friend istream& operator >>(istream& input,Complex& c);
private:
    double real;
    double imag;
};
//下面定义成员函数
    Complex Complex::operator+(const Complex &c2)
    {
        Complex c;
        c.real=real+c2.real;
        c.imag=imag+c2.imag;
        return c;
    }
    Complex Complex::operator-(const Complex &c2)
    {
        Complex c;
        c.real=real-c2.real;
        c.imag=imag-c2.imag;
        return c;
    }
    Complex Complex::operator*(const 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/(const Complex &c2)
    {
        Complex c;
        c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
        c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
        return c;
    }
void Complex::display()
{
    cout<<real;
    if(imag>0)
        cout<<'+'<<imag<<'i'<<endl;
    else
        cout<<imag<<'i'<<endl;
}
Complex operator-(Complex &c2)
{
    Complex c;
    return (c-c2);
}
ostream& operator <<(ostream& output,const Complex& c)
{
    output<<'('<<c.real;
    if(c.imag>=0)
        output<<'+';
    output<<c.imag<<"i)";
    return output;
}
istream& operator >>(istream& input,Complex& c)
{
    int a,b;
    char sign,i;
    do
    {
        cout<<"input (a+bi or a-bi)\n";
        input>>a>>sign>>b>>i;
    }while(!(sign=='+'||sign=='-')&&i=='i');
    c.real=a;
    c.imag=(sign=='+')?b:-b;
    return input;
}
//下面定义用于测试的main()函数
int main()
{
    Complex c1,c2,c3;
    cout<<"c1: "<<endl;;
    cin>>c1;
    cout<<"c2: "<<endl;
    cin>>c2;

    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();
    c3=-c3;
    c3.display();
    return 0;
}

技术分享

又成功一个,耶

第九周(运算符重载复数类)

标签:c++ 生活

原文地址:http://blog.csdn.net/wangzhongwangmin/article/details/45675813

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!