标签:
常规的运算符只能计算基本类型的变相,没办法将对象相加或者相减
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;
}
标签:
原文地址:http://blog.csdn.net/ttf1993/article/details/46313911