运算符重载

运算符重载

operatorOP(argument-list) 是运算符重载的方法,例如operator+()重载+,op必须是已经存在的运算符

OP是[]的话,将重载[]运算符

而且可以对t1=t2+t3+t4这种方式的进行重载。

运算符重载的限制

1.重载之后的运算符必须至少有一个操作数是用户定义的类型,这样可以防止用户修改标准类型重载运算符,所以你不能将两个int相加重载成两个int相减少。

2.使用操作符时不能违反原来的句法规则,比如不可以使用%va这种

3.不能使用不存在的运算符,不能修改运算符的优先级。

4.不能重载 sizeof 类运算符 ?; typeid 等

5.= 和()和[]和->只能通过成员函数重载

实例

下面重载了运算符+和-来运算时间的加减共三个文件

#ifndef HAD
#define HAD
class time{
    private:
        int hours;
        int mins;
    public:
        time();
        time(int h, int m = 0);
        void Addmin(int m);
        void AddHr(int h);
        void reset(int h = 0, int m = 0);
        time operator+(const time &t) const;
        void show() const;
        time operator-(const time &t) const;
};
#endif
#include<iostream>
#include"mytime0.h"
using std::cout;
time::time()
{
    hours = 0;
    mins = 0;
}
time::time(int h,int m)
{
    hours = h;
    mins = m;
}
void time::Addmin(int m)
{
    mins += m;
    while(mins>=60)
    {
        hours++;
        mins -= 60;
    }
}
void time::AddHr(int h)
{
    hours += h;
}
void time::reset(int h,int m)
{
    hours = h;
    mins = m;
}
time time::operator+(const time & t)const//参数用引用加快效率,返回值不用引用是因为如果使用引用,被引用的将会在函数结束的之后删除
{
    time sum;
    sum.mins = mins + t.mins;
    sum.hours = hours + t.hours + sum.mins / 60;
    sum.mins %= 60;
    return sum;
}
time time::operator-(const time & t)const//参数用引用加快效率,返回值不用引用是因为如果使用引用,被引用的将会在函数结束的之后删除
{
    time sum;
    if(mins>=t.mins)
    {
    sum.mins = mins - t.mins;
    sum.hours = hours - t.hours;
    }
    else
    {
        sum.mins = mins + 60 - t.mins;
        sum.hours = hours - t.hours - 1;
    }
    return sum;
}
void time::show() const
{
    cout << hours << " hours," << mins << " minutes";
}


#include<iostream>
#include"mytime0.cpp"
int main()
{
    using std::cout;
    using std::endl;
    time plan;
    time code(2, 40);
    time fix(5, 55);
    time total;

    cout << "plantime :=";
    plan.show();
    cout << endl;
    
    cout << "codetime :=";
    code.show();
    cout << endl;
    
    cout << "fixtime  :=";
    fix.show();
    cout << endl;

    total = code + fix;
    cout << "totaltime:=";
    total.show();
    cout << endl;

    total = fix-code;
    cout << "totaltime-:=";
    total.show();
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值