博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一元运算符重载
阅读量:4694 次
发布时间:2019-06-09

本文共 2289 字,大约阅读时间需要 7 分钟。

就是操作数只有一个 比如自增自减的

有两种方式实现重载

一种是所谓成员函数重载,

调用方式:1. @a; 2. a.operator@()

另一种是作为友元函数重载

调用方式:1 @a; 2.operator(a)

先说第一种吧,举个例子

需要注意到,一元运算符作为成员函数重载,里面是没有参数的

class x

{
...
T operator@(){...};
//等价于T operator@(x *this) this 是 指针参数由系统自动添加的是一个隐含参数
};
T为返回类型,@为重载的运算符

woc,我写的时候不知道有time这个类库,我重名了。改了半个小时才意识到,人都快被气死了

1 #include
2 using namespace std; 3 4 class Time 5 { 6 private: 7 int h,m,s; 8 public: 9 Time(int hour,int minute,int second);10 Time& operator++();11 void display();12 13 };14 15 Time::Time(int hour,int minute,int second)16 {17 h = hour;18 if(h == 24) h = 0;19 m = minute;20 if(m == 60) m = 0;21 s = second;22 if(s == 60) s = 0;23 }24 25 26 Time& Time::operator++()27 {28 ++s;29 if(s == 60)30 {31 s = 0;32 ++m;33 if(m == 60)34 {35 m = 0;36 ++h;37 if(h == 24) h = 0;38 }39 }40 return *this;41 }42 43 void Time::display()44 {45 cout << h << ":" << m << ":" << s << endl;46 }47 48 void test()49 {50 Time t0(23,59,59);51 t0.display();52 ++t0;//显氏调用53 t0.display();54 t0.operator++();//隐氏调用55 t0.display();56 }57 58 int main()59 {60 test();61 return 0;62 }
View Code

 

作为友元函数重载

1 #include
2 using namespace std; 3 4 class Time 5 { 6 private: 7 int h,m,s; 8 public: 9 Time(int hour,int minute,int second);10 friend Time& operator++(Time &t);11 void display();12 13 };14 15 Time::Time(int hour,int minute,int second)16 {17 h = hour;18 if(h == 24) h = 0;19 m = minute;20 if(m == 60) m = 0;21 s = second;22 if(s == 60) s = 0;23 }24 25 26 Time& operator++(Time &t)27 {28 ++t.s;29 if(t.s == 60)30 {31 t.s = 0;32 ++t.m;33 if(t.m == 60)34 {35 t.m = 0;36 ++t.h;37 if(t.h == 24) t.h = 0;38 }39 }40 return t;41 }42 43 void Time::display()44 {45 cout << h << ":" << m << ":" << s << endl;46 }47 48 void test()49 {50 Time t0(23,59,59);51 t0.display();52 ++t0;//显氏调用53 t0.display();54 operator++(t0);//隐氏调用55 t0.display();56 }57 58 int main()59 {60 test();61 return 0;62 }

 

转载于:https://www.cnblogs.com/mch5201314/p/11590194.html

你可能感兴趣的文章
tooltips插件
查看>>
vim复制内容到系统剪贴板
查看>>
PHP 二叉查找树
查看>>
How to Run a Program as an Administrator in Windows 7
查看>>
成为php高手的5个秘诀(转)
查看>>
单例模式
查看>>
利用css样式画各种图形--初步、进阶、高级(一)
查看>>
【洛谷P1541】乌龟棋(NOIP2010)
查看>>
.NET Core 1.0、ASP.NET Core 1.0和EF Core 1.0简介
查看>>
linux常用命令(1)
查看>>
面向对象
查看>>
入侵检测-转载
查看>>
最大熵模型(Maximum Etropy)—— 熵,条件熵,联合熵,相对熵,互信息及其关系,最大熵模型。。...
查看>>
Git相关操作一
查看>>
阿里盒马领域驱动设计实践
查看>>
VS2005中的一个小BUG:关于Dropdownlist无法Datadinding的解决方法。
查看>>
frame-框架
查看>>
IOS开发学习笔记034-UIScrollView-xib实现分页
查看>>
(转)AS3多人游戏开发—同步人物移动1
查看>>
Djang学习笔记-1
查看>>