码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-01 18:49:27      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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

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;
}

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

标签:

原文地址:http://blog.csdn.net/ttf1993/article/details/46313911

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!