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

第九周项目一-复数类的中的运算符重载(续)

时间:2015-05-16 14:55:36      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

在复数类中的运算符重载基础上
(1)再定义一目运算符 -,-c相当于0-c。

(2)定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然

/*
* Copyright (c) 2015,烟台大学计算机学院
* All right reserved.
* 作者:赵嵩
* 文件:Demo.cpp
* 完成时间:2015年05月16日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
class Complex
{
public:
    Complex()
    {
        real=0;
        imag=0;
    }
    Complex(double r,double i)
    {
        real=r;
        imag=i;
    }
    friend ostream& operator << (ostream& output, const Complex& c);
    friend istream& operator >> (istream& input, Complex& c);
    Complex operator-();
    Complex operator+(const Complex &c2);
    Complex operator-(const Complex &c2);
    Complex operator*(const Complex &c2);
    Complex operator/(const Complex &c2);
    void display();
private:
    double real;
    double imag;
};
//下面定义成员函数
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 complex number(a+bi或a-bi):";
        input>>a>>sign>>b>>i;
    }
    while(!((sign=='+'||sign=='-')&&i=='i'));
    c.real=a;
    c.imag=(sign=='+')?b:-b;
    return input;
}
Complex Complex::operator-()
{
    return(-*this);
}
Complex Complex::operator+(const Complex &c2)
{
    Complex a;
    a.real=real+c2.real;
    a.imag=imag+c2.imag;
    return a;
}
Complex Complex::operator-(const Complex &c2)
{
    Complex a;
    a.real=real-c2.real;
    a.imag=imag-c2.imag;
    return a;
}
Complex Complex::operator*(const Complex &c2)
{
    Complex a;
    a.real=real*c2.real;
    a.imag=imag*c2.imag;
    return a;
}
Complex Complex::operator/(const Complex &c2)
{
    Complex a;
    a.real=real/c2.real;
    a.imag=imag/c2.imag;
    return a;
}
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
//下面定义用于测试的main()函数
int main()
{
    Complex c1,c2,c3;
    cout<<"c1: "<<endl;;
    cin>>c1;
    cout<<"c2: "<<endl;
    cin>>c2;
    cout<<"c1="<<c1<<endl;
    cout<<"c2="<<c2<<endl;
    c3=c1+c2;
    cout<<"c1+c2="<<c3<<endl;
    c3=c1-c2;
    cout<<"c1-c2="<<c3<<endl;
    c3=c1*c2;
    cout<<"c1*c2="<<c3<<endl;
    c3=c1/c2;
    cout<<"c1/c2="<<c3<<endl;
    return 0;
}

运行结果:

技术分享

第九周项目一-复数类的中的运算符重载(续)

标签:

原文地址:http://blog.csdn.net/zs9528/article/details/45767969

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