普通运算符重载
-
C++准许以运算符命名函数
string love = "i";love += " love";//+(love, " love"); love += " you";//+(love, " you");cout<< "i love you";// <<(cout, "i love you");
-
运算符分类
数学运算符
+ - * / ++ --
关系运算符
== >= <= !=
特殊运算符
[ ]= 赋值运算符 ()仿函数 << 输出运算符
数学运算符关系运算符例子
#include <stdio.h>
#include <unistd.h>class myTimer{
public:myTimer(){hour = 0;min = 0;sec = 0;}~myTimer(){}void addtimer(int sec = 1){this->sec = this->sec + sec;}void showtime(){printf("%02d:%02d:%02d\n",hour / 3600,min / 60,sec % 60);}//重载5bool operator == (myTimer &x){return (sec == x.sec && min == x.min && hour == x.hour) ? true : false;}//重载4 ++tmyTimer operator++(){sec++;return *this;}/********所以一般写代码循环尽量用++i,因为i++会有拷贝过程******///重载3 t++myTimer operator ++ (int){myTimer tmp = *this;//先记录自己sec++;//自己++return tmp;//返回之前的}//重载2myTimer operator + (int t){myTimer tmp;tmp.sec = sec + t;return tmp;}//重载1myTimer operator + (myTimer &x){myTimer tmp;tmp.sec = sec + x.sec;tmp.min = x.min;tmp.hour = x.hour;return tmp;}
private:int hour;int min;int sec;
};int main(int argc, char const *argv[])
{myTimer t1;t1.addtimer(3);myTimer t2;t2.addtimer(6);myTimer t3;t3 = t2++;//重载3 先赋值再加printf("重载3 ");t3.showtime();t3 = ++t2;//重载4 先加再赋值printf("重载4 ");t3.showtime();printf("重载5 ");if(t2 == t3)//重载5printf("==\n");elseprintf("!=\n");printf("重载1 ");t3 = t1 + t2;//重载1t3.showtime();printf("重载2 ");t3 = t3 + 2;//重载2t3.showtime();printf("重载5 ");if(t2 == t3)//重载5printf("==\n");elseprintf("!=\n");return 0;
}
结果