一元运算符重载

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

有两种方式实现重载

一种是所谓成员函数重载,另一种是作为友元函数重载

先说第一种吧,举个例子

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

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

猜你喜欢

转载自www.cnblogs.com/mch5201314/p/11590194.html