1.概念
请描述什么是运算符重载,运算符重载如何实现?
C++提供的运算符重载机制能够实现将已有运算符应用到新的数据类型变量上,赋予运算符新的含义。
有两种方法可以实现运算符重载,它们是:类的成员函数方式和有友元函数方式。
2.可以重载的运算符
3.运算符分类
4.实现形式
5.函数实例
函数重载 +
#include <stdio.h>
#include <unistd.h>
class Timer{
public:
Timer(){
hour = 0;
min = 0;
sec = 0;
}
~Timer(){
}
void additTimer(int sec = 1){
this->min = (this->sec+sec)/60;
this->sec += sec%60;
}
void show(){
printf("%2d:%2d:%2d\n",hour,min,sec);
}
Timer operator+(int sec)//函数重载t2=t1+5
{
Timer tem;
tem.sec = this->sec+sec;
return tem;
}
Timer operator+(Timer &x)//函数重载t2=t1+t
{
Timer tem;
tem.sec = sec+x.sec;
tem.min = min+x.min;
tem.hour = hour+x.hour;
return tem;
}
private:
int hour;
int min;
int sec;
};
int main(int argc,char *argv[])
{
Timer t;
t.additTimer(3);
Timer t1;
t.additTimer(5);
Timer t2;
t2 = t + t1; //函数重载t2=t1+t
t2.show();
t2=t2+5; //函数重载t2=t1+5
t2.show();
return 0;
}
函数重载 前++,后++, C++推荐使用前++
#include <stdio.h>
#include <unistd.h>
class Timer{
public:
Timer(){
hour = 0;
min = 0;
sec = 0;
}
~Timer(){
}
void additTimer(int sec = 1){
this->min = (this->sec+sec)/60;
this->sec += sec%60;
}
void show(){
printf("%2d:%2d:%2d\n",hour,min,sec);
}
Timer operator+(int sec)//函数重载t2=t1+5
{
Timer tem;
tem.sec = this->sec+sec;
return tem;
}
Timer operator+(Timer &x)//函数重载t2=t1+t
{
Timer tem;
tem.sec = sec+x.sec;
tem.min = min+x.min;
tem.hour = hour+x.hour;
return tem;
}
Timer operator++(int)//函数重载t2++
{
Timer tem = *this;
sec++;
return tem;
}
Timer operator++()//函数重载++t2
{
sec++;
return *this;
}
private:
int hour;
int min;
int sec;
};
int main(int argc,char *argv[])
{
Timer t;
t.additTimer(3);
Timer t1;
t.additTimer(5);
Timer t2;
t2 = t + t1; //函数重载t2=t1+t
t2.show();
t2=t2+5; //函数重载t2=t1+5
t2.show();
Timer t3 = t2++; //函数重载t2++
t3.show();
t2.show();
Timer t4 = ++t2; //函数重载++t2
t4.show();
t2.show();
return 0;
}
函数重载 ==
#include <stdio.h>
#include <unistd.h>
class Timer{
public:
Timer(){
hour = 0;
min = 0;
sec = 0;
}
~Timer(){
}
void additTimer(int sec = 1){
this->min = (this->sec+sec)/60;
this->sec += sec%60;
}
void show(){
printf("%2d:%2d:%2d\n",hour,min,sec);
}
Timer operator+(int sec)//函数重载t2=t1+5
{
Timer tem;
tem.sec = this->sec+sec;
return tem;
}
Timer operator+(Timer &x)//函数重载t2=t1+t
{
Timer tem;
tem.sec = sec+x.sec;
tem.min = min+x.min;
tem.hour = hour+x.hour;
return tem;
}
Timer operator++(int)//函数重载t2++
{
Timer tem = *this;
sec++;
return tem;
}
Timer operator++()//函数重载++t2
{
sec++;
return *this;
}
bool operator==(Timer &x) //函数重载 ==
{
if(sec==x.sec && min==x.min && hour==x.hour)
return true;
return false;
}
private:
int hour;
int min;
int sec;
};
int main(int argc,char *argv[])
{
Timer t;
t.additTimer(3);
Timer t1;
t.additTimer(5);
Timer t2;
t2 = t + t1; //函数重载t2=t1+t
t2.show();
t2=t2+5; //函数重载t2=t1+5
t2.show();
Timer t3 = t2++; //函数重载t2++
t3.show();
t2.show();
Timer t4 = ++t2; //函数重载++t2
t4.show();
t2.show();
if(t2 == t3) //函数重载 ==
printf("OK..time out!\n");
return 0;
}