10.3运算符重载

#include <iostream>

using namespace std;

//定义一个复数类
class Complex
{
private:
    int real;   //实部
    int vir;    //虚部
public:
    Complex(){}
    Complex(int r, int v):real(r),vir(v){}

    void show(){
        if(vir > 0){
            cout<<real<<" + "<<vir<<"i"<<endl;
        }else{
            cout<<real<<vir<<"i"<<endl;
        }
    }

    const Complex operator-(const Complex &R)const {
        Complex c;

        c.real = real - R.real;
        c.vir = vir - R.vir;

        return c;
    }

    //成员函数版实现关系运算符重载
    bool operator>(const Complex &R)const {
        return real>R.real&&vir>R.vir;
    }

    int & operator[](const int index) {
        if(1 == index){
            return vir;
        }else if(0 == index){
            return real;
        }else{
            cout<<"段错误"<<endl;
        }
    }

    Complex &operator+=(const Complex &R) {

        real += R.real;
        vir += R.vir;

        return *this;   //返回自身的引用
    }

    //重载负号运算符
    Complex operator-()const {
        Complex c;

        c.real = -real;
        c.vir = -vir;

        return c;
    }

    friend const Complex operator+(const Complex &L,const Complex &R);
};

//全局函数版实现加号运算符重载:实部加实部,虚部加虚部
const Complex operator+(const Complex &L,const Complex &R){
    //定义一个临时空间
    Complex c;

    c.real = L.real + R.real;
    c.vir = L.vir + R.vir;

    return c;
}

int main()
{
    Complex c1(5,7);
    c1.show();

    Complex c2(4,-3);
    c2.show();

    Complex c3 = c1+c2;
    c3.show();

    Complex c4 = c1-c2;
    c4.show();

    if(c3 > c4){
        cout<< "yes" << endl;
    }else{
        cout<< "no" << endl;
    }

    c3[0] = 5;
    c3.show();

    c3 += c2 += c1;

    c1.show();
    c2.show();
    c3.show();

    Complex c5 = -c4;
    c5.show();

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值