一. 概念
1. 在operate函数内实现你想实现的具体的运算操作, 这样一来不单单只可以对普通的数进行加减操作, 可以对类进行加减操作, 在operate函数内实现的加减的具体实现过程就可以。
2. 运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
3. C++准许以运算符命名函数!!!
string a = “hello”;
a += “ world”;// +(a, “world”);
cout<<“hello”; // <<(cout, “hello”);
二. 可以重载的运算符
不可重载的运算符
三. 运算符分类
数学运算符
+ - * / ++ --
关系运算符
== >= <= !=
特殊运算符
[ ]
= 赋值运算符
( ) 仿函数
<< 输出运算符
四.代码展示
#include<stdio.h>
#include<unistd.h>
class Timer {
public:
Timer():hour(0), min(0), sec(0) //构造函数初始化列表
{
}
~Timer() //析构函数
{
}
int Timer_add(int sec) {
this->hour = this->hour + ((this->min + (this->sec + sec) / 60) /60) % 24;
this->min = (this->min + (this->sec + sec) / 60) % 60; //取整
this->sec = (this->sec + sec) % 60; //取模
}
void Timer_show() {
printf("%02d-%02d-%02d\n", hour, min, sec);
}
Timer operator+(Timer &x) { //加法运算符重载
Timer temp;
temp.hour = this->hour + x.hour;
temp.min = this->min + x.min;
temp.sec = this->sec + x.sec;
return temp;
}
Timer operator+(int sec) { //类 + int运算符重载
Timer temp = *this;
temp.sec = this->sec + sec;
return temp;
}
Timer operator-(Timer &x) { //减法运算符重载
Timer temp;
temp.hour = this->hour - x.hour;
temp.min = this->min - x.min;
temp.sec = this->sec - x.sec;
return temp;
}
Timer operator++(int){ //后加加运算符重载
Timer temp = *this;
temp.sec = this->sec++;
return temp;
}
Timer operator++() { //前加加运算符的重载
sec++;
return *this;
}
private:
int hour;
int min;
int sec;
};
int main(int argc, const char *argv[])
{
Timer a;
while(1) {
a.Timer_add(1); //每次定时一秒
a.Timer_show();
sleep(1);
}
#if 0
Timer a1;
//1.
a1.Timer_add(2);
a1.Timer_show();
Timer a2;
//2.
a2.Timer_add(10);
a2.Timer_show();
//3.
Timer a3 = a1 + a2;
a3.Timer_show();
//4.
Timer a4 = a2 - a1;
a4.Timer_show();
//5.
a1++;
a1.Timer_show();
//6.
++a1;
a1.Timer_show();
//7.
a1 = a1 + 100; //a1这样写为了接收temp的返回值
a1.Timer_show();
#endif
return 0;
}