【C++总结】运算符重载

常规的运算符只能计算基本类型的变相,没办法将对象相加或者相减

Timer t1;
Timer t2;
t1 + t2;//t1和t2是对象,不能相加

要想能实现对象的运算,必须要重载运算符

成员函数形式重载运算符

重载运算符只需要把函数名换成operator+

const Timer operator+(Timer t);//重载+号运算符,调用的时候默认有个this形参

const Timer Timer::operator+(Timer t) {//千万不能返回引用
    Timer time;
    time.hour = this->hour + t.hour;
    time.minute = this->minute + t.minute;
    return time;
}

使用友元函数形式重载运算符

使用友元函数形式的重载,参数形式要显示给出,成员函数是一个,这边就该是两个

friend const Timer operator-(Timer t1, Timer t2);//使用友元形式重载

const Timer operator-(Timer t1, Timer t2) {//两个参数显示给出
    Timer time;
    time.hour = t1.hour - t2.hour;
    time.minute = t1.minute - t2.minute;
    return time;
}

重载<<输出操作符

使用友元形式。这样就可以直接输出对象。cout << t1;

friend const ostream& operator<<(ostream &os, Timer t);//可以直接输出对象

const ostream& operator<<(ostream &os, Timer t) {//和java中toString一样
    os << "时间是:" << t.hour << ":" << t.minute << endl;
    return os;
}

综合例子

#include <iostream>
using namespace std;

class Timer {
public:
    int hour;
    int minute;
public:
    Timer(){}

    Timer(int hour, int minute):hour(hour), minute(minute) {}

    const Timer operator+(Timer t);//重载+号运算符

    friend const Timer operator-(Timer t1, Timer t2);//重载-号运算符

    friend const ostream& operator<<(ostream &os, Timer t);//重载<<
};

const Timer Timer::operator+(Timer t) {
    Timer time;
    time.hour = this->hour + t.hour;
    time.minute = this->minute + t.minute;
    return time;
}

const Timer operator-(Timer t1, Timer t2) {
    Timer time;
    time.hour = t1.hour - t2.hour;
    time.minute = t1.minute - t2.minute;
    return time;
}


const ostream& operator<<(ostream &os, Timer t) {
    os << "时间是:" << t.hour << ":" << t.minute << endl;
    return os;
}

int main() {
    Timer t1 = {2, 15};
    Timer t2 = {3, 15};

    Timer t3 = t1 + t2;
    cout << t3.hour << "-------" << t3.minute << endl;
    cout << t3;

    Timer t4 = t2 - t1;
    cout << t4.hour << "-------" << t4.minute << endl;
    cout << t4;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值