国庆day4

C++运算符重载实现的过程

#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=this->real+R.real;
        c.vir=this->vir+R.vir;
        return c;
    }
    //减法运算符重载
    const Complex operator-(const Complex &R)const{
        Complex c;
        c.real=this->real-R.real;
        c.vir=this->vir-R.vir;
        return c;
    }
    //关系运算符重载
    bool operator>(const Complex &R)const
    {
        return this->real>R.real&&this->vir>R.vir;
    }
    bool operator<(const Complex &R)const
    {
        return this->real<R.real&&this->vir<R.vir;
    }
    //累加法运算符重载
    Complex & operator+=(const Complex &R){
        this->real+=R.real;
        this->vir+=R.vir;
        return *this;
    }
    //累减法运算符重载
    Complex & operator-=(const Complex &R){
        this->real-=R.real;
        this->vir-=R.vir;
        return *this;
    }
    //前置自增运算符重载
    Complex & operator++(){
        ++this->real;
        ++this->vir;
        return *this;
    }
    //后置自增运算符重载
    Complex operator++(int){
        Complex c;
        c.real=this->real++;
        c.vir=this->vir++;
        return c;
    }
    //中括号运算符重载
    int & operator[](int index){
        if(0==index){
            return real;
        }
        else if(1==index){
            return vir;
        }
    }
    //将全局函数版实现的输出运算符重载函数设置成友元
    friend ostream &operator<<(ostream &L, Complex &c);
};
//输出运算符重载
ostream & operator<<(ostream &L,Complex &c){
    if(c.vir>=0){
        L<<c.real<<"+"<<c.vir<<"i"<<endl;
    }
    else{
        L<<c.real<<c.vir<<"i"<<endl;
    }
    return L;
}
 
int main()
{
    Complex c(5,3);
    c.show();
 
    Complex c1(2,-4);
    c1.show();
 
    Complex c2=c+c1;
    c2.show();
 
    Complex c3=c-c1;
    c3.show();
 
    if(c1 < c2)
    {
        cout<<"yes"<<endl;
    }else
    {
        cout<<"no"<<endl;
    }
    c3+=c1;
    c3.show();
    c3++;
    c3.show();
    ++c;
    c.show();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值