C++中运算重载和定时器函数的实现

一. 概念

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@daiwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值