C++运算符重载理解

重载: 实现函数对应的载入。

运算符重载:实现类的一些操作,类不能实现自增自减,类可以理解成一个数据类型。

实现类的重载的方法:友元函数实现,以及类内声明和类外实现(学完STL再补充)

    友元函数实现运算符的重载(跟函数声明类似)
    五个特殊运算符的重载:   =,++,--,<<,>>的重载

PS:运算符重载很重要跟后面学STL很有关联,每个运算符都很重要

#include<iostream>
using namespace std;
class Will
{
    int m_clo;
    int m_ll;
public:
    Will(int a,int  b)
    {
        m_clo = a;
        m_ll = b;
    }
    Will():m_clo(0),m_ll(0) //无参构造也要整一个啊!!!!
    {}
    Will operator +(const Will &r1)const;//+运算符的重载
    friend void show(const Will& a);
    Will operator *(const Will &r2)const;//*运算符的重载
    bool operator <(const Will &r3)const;//<运算符的重载
    bool operator ==(const Will &r4)const;// ==运算符的重载
    friend Will operator -(const Will &r5,const Will &r6);
};
Will operator -(const Will &r5,const Will &r6)
{

    Will one ;
    one.m_clo = r5.m_clo - r6.m_clo;
    one.m_ll = r5.m_ll - r6.m_ll;
    return one;
}
void show(const Will& a)
{

    cout<<a.m_clo<<" "<<a.m_ll<<endl;
}
Will Will::operator +(const Will &r1)const
{
    Will one;
    one.m_clo = this->m_clo+r1.m_clo;
    one.m_ll = this->m_ll + r1.m_ll;
    return one;
}

Will Will::operator *(const Will &r2)const
{
    Will one;
    one.m_clo = m_clo * r2.m_clo;
    one.m_ll = m_ll* r2.m_ll;
    return one;
}

bool Will::operator <(const Will &r3)const
{
    return this->m_ll*r3.m_clo < this->m_clo* r3.m_ll;
}

bool Will::operator ==(const Will &r4)const
{
    return this->m_clo==r4.m_clo&&this->m_ll == r4.m_ll;
}


int main()
{
    Will r1(3,4);
    Will r2(3,4);

    Will r3;
    cout<<"实现+"<<endl;
    r3 = r1+ r2;
    show(r3);

    cout<<"实现*"<<endl;
    Will r4;
    r4 = r1*r2;
    show(r4);

     cout<<"实现<"<<endl;
     cout<<(r1 < r2 ?"true":"false")<<endl;
      cout<<"实现=="<<endl;
     cout<<(r1 == r2 ? "true":"false")<<endl;
     cout<<"实现-"<<endl;
    Will r5;
    r5 = r1 - r2;
    show(r5);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值