您的位置:首页 > 编程语言 > C语言/C++

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

2015-06-01 17:18 323 查看
常规的运算符只能计算基本类型的变相,没办法将对象相加或者相减

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: