一元运算符重载

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

有两种方式实现重载

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

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

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

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

先说第一种吧,举个例子

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

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

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

 1 #include<bits/stdc++.h>
 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<bits/stdc++.h>
 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值