C++——运算符重载

 继续完成my_string 类的书写,主要完成运算符重载:

+=运算符:operator+=

下标运算符:operator[]

加法运算符:operator+

关系运算符:> 、 <、==

要求:自己分析函数,该加const的要准确加上

#include <iostream>

using namespace std;
class my_string
{
private:
    int rea;//实部
    int vir;//虚部
    char *str;
public:
    my_string(){}
    my_string(int r,int v):rea(r),vir(v){}
    void show()
    {
        cout<<rea<<"+"<<vir<<"i"<<endl;
    }
    //实现+运算符重载:实部+实部  虚部+虚部

    const my_string operator+(const my_string& R)const
    {
        my_string temp;
        temp.rea=this->rea+R.rea;
        temp.vir=this->vir+R.vir;
        return temp;
    }
    friend const my_string operator-(const my_string& L,const my_string& R);
    //实现+=运算符重载
    my_string & operator+=(const my_string R)
    {
        this->rea+=R.rea;
        this->vir+=R.vir;
        return  *this;
    }
    friend my_string & operator-=(my_string &L,const my_string &R);
    //实现>运算符重载
    bool operator>(const my_string R)
    {
        return  this->rea>R.rea&&this->vir>R.vir;
    }
    //实现<运算符重载
    bool operator<(const my_string R)
    {
        return  this->rea<R.rea&&this->vir<R.vir;
    }
    //实现==运算符重载
    bool operator==(const my_string R)
    {
        return  this->rea==R.rea&&this->vir==R.vir;
    }
    //实现-(负号)运算符重载
    const my_string operator-()const
    {
        my_string temp;
        temp.rea=-this->rea;
        temp.vir=-this->vir;
        return temp;
    }
    //实现后置++
    my_string operator++(int)
    {
        my_string temp;
        temp.rea=this->rea++;
        temp.vir=this->vir++;
        return temp;
    }
    //实现下标
    char operator[](const int n)
    {
        char temp;
        temp=this->str[n];
        return temp;
    }


};
//负号
const my_string operator-(const my_string& L,const my_string& R)
{
    my_string temp;
    temp.rea=L.rea-R.rea;
    temp.vir=L.vir-R.vir;
    return temp;
}
my_string & operator-=(my_string &L,const my_string &R)
{
    L.rea-=R.rea;
    L.vir-=R.vir;
    return L;

}

int main()
{
    my_string c1(3,6);
    c1.show();
    my_string c2(6,7);
    c2.show();
    my_string c3;
    c3+=c1;
    c3.show();
    my_string c4(6,8);
    c4=c1+c2;
    c4.show();

    if(c1>c2)
    {
        cout<<"yes"<<endl;
    }
    else
    {
        cout<<"no"<<endl;
    }
    if(c1==c2)
    {
        cout<<"yes"<<endl;
    }
    else
    {
        cout<<"no"<<endl;
    }
    if(c1<c2)
    {
        cout<<"yes"<<endl;
    }
    else
    {
        cout<<"no"<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值