重载和运算

/*
* 程序的版权和版本声明部分:
* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作    者:周经纬
* 完成日期:2014年 4月 22日
* 版 本 号:v12.1
* 重载和运算,
* 输入描述:无
* 问题描述:。
* 程序输出:
* 问题分析:略
* 算法设计:略
*/

#include <iostream>

using namespace std;

class Complex
{
public:
    Complex()
    {
        real=0;
        imag=0;
    }
    Complex(double r,double i)
    {
        real=r;
        imag=i;
    }
    Complex operator+(double x);
    Complex operator-(double x);
    friend Complex operator-(Complex &c);
    friend Complex operator+(double x,Complex c);
    friend Complex operator-(double x,Complex c);
    friend istream& operator>>(istream& input,Complex &s1);
    friend ostream& operator<<(ostream& output,Complex &s1);

    void display();
    double geta()
    {
        return real;
    }
    double getb()
    {
        return imag;
    }
private:
    double real;
    double imag;
};
void Complex::display()
{

    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex Complex::operator+(double x)
{
    return Complex(x+real,imag);
}
Complex Complex::operator-(double x)
{
    return Complex(real-x,imag);
}
Complex operator+(double x,Complex c)
{
    return Complex(x+c.real,c.imag);
}
Complex operator-(double x,Complex c)
{
    return Complex(x-c.real,c.imag);
}
Complex operator-(Complex &c)
{
    Complex c1;
    c1.imag=0-c.imag;
    c1.real=0-c.real;
    return c1;
}
istream & operator >>(istream &putin,Complex&c)
{
    putin>>c.real>>c.imag;
    return  putin;

}
ostream & operator <<(ostream &output,Complex&c)
{
    output<<"("<<c.real;
    if(c.imag>0)
        output<<"+";
    output<<c.imag<<"i"<<")"<<endl;
    return output;
}


int main()
{
    Complex c1(-1,4),c2;

    double d=4;
    cout<<"c1+d=";
    c2=c1+d;
    c2.display();
    cout<<"c1-d=";
    c2=c1-d;
    c2.display();
    cout<<"d-c1=";
    c2=d-c1;
    c2.display();
    cout<<"d+c1=";
    c2=d+c1;
    c2.display();
    cout<<"-c2=";
    c2=-c2;
    cout<<c2;

}

对<<.>>这两个运算符的重载还是不理解,看了一个小时了,像喝醉了的感觉-----。梦佳跟大飞的对这两个符号的重载代码不一样,越看越迷茫,本来就没看懂提议,这下更一头雾水了,晚上回去再看看


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值