C++学习笔记之 操作符重载
操作符重载
定义
运算符重载只是一种“语法上的方便”,也就是一种函数的调用方式
加号运算符重载
案例
现在实现了一个计时器类
// zjy_timer.h
#ifndef ZJY_TIMER_H
#define ZJY_TIMER_H
#include <ctime>
#include <cstring>
namespace zjy {
class Timer
{
public:
void start();
void stop();
double time;
private:
clock_t m_start;
clock_t m_end;
};
}
#endif // ZJY_TIMER_H
// ------------------------------------------------------------------------
// timer.cpp
#include "zjy_timer.h"
void zjy::Timer::start()
{
this->time = 0.0;
this->m_start = clock();
}
void zjy::Timer::stop()
{
this->m_end = clock();
this->time = (double)(this->m_end - this->m_start);
}
现在有需求实现如下操作
Timer t1,t2;
//...
cout << t1 + t2 << endl;
实现
1. 通过成员函数函数重载
class Timer
{
public:
void start();
void stop();
double time;
Timer operator+(Timer &t)
{
Timer rt;
rt.time = this->time + t.time;
return rt;
}
private:
clock_t m_start;
clock_t m_end;
};
调用方法:
t1 + t2
,本质:t1.operator+(t2)
2. 通过全局函数重载
Timer operator+(Timer &t1,Timer &t2)
{
Timer rt;
rt.time = t2.time + t1.time;
return rt;
}
调用方法:
t1 + t2
,本质:operator+(t1,t2)