88.++ --的重载

  • shortsafe operator ++() 先自增再引用
  • shortsafe operator ++(int) 先引用再自增后面,需要副本(先用副本进行操作,然后再进行自己类的++改变数据)(返回的都是修改后的数据)
  • ()可以把对象名当做括号来操作

代码示例

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <iostream>
 3 using namespace std;
 4 
 5 //shortsafe operator ++() 先自增再引用
 6 //shortsafe operator ++(int) 先引用再自增后面,需要副本
 7 //()可以把对象名当做括号来操作
 8 
 9 class shortsafe
10 {
11 public:
12     unsigned short sh = 0;
13 public:
14     //没有参数++或者--在前面(先自增再引用)
15     shortsafe operator ++()
16     {
17         
18         if (this->sh < 65535)
19         {
20             this->sh++;
21         }
22         else
23         {
24             abort();
25         }
26         return *this;
27     }
28 
29     //后加(先引用再自增)
30     shortsafe operator ++(int)
31     {
32         //先引用副本
33         shortsafe tmp;
34         tmp.sh = this->sh;
35         if (this->sh < 65535)
36         {
37             this->sh++;
38         }
39         else
40         {
41             abort();
42         }
43         return tmp;
44     }
45 
46     //前减(先自减再引用)
47     void operator --()
48     {
49         if (this->sh >0)
50         {
51             this->sh++;
52         }
53         else
54         {
55             abort();
56         }
57     }
58 
59     unsigned short operator()()
60     {
61         return this->sh;
62     }
63 
64     shortsafe operator +(unsigned int num)
65     {
66         shortsafe tmp;
67         if (tmp.sh + num <= 65535)
68         {
69             tmp.sh += num;
70         }
71         else
72         {
73             abort();
74         }
75     }
76 };
77 
78 
79 void main()
80 {
81     shortsafe shsafe;
82     shsafe.sh = 0;
83     //重载不改变运算的优先级
84     ++shsafe;
85     cout << shsafe.sh << endl;
86     cout << shsafe() << endl;
87     cin.get();
88 }

 

posted @ 2018-03-18 17:49  喵小喵~  阅读(135)  评论(0编辑  收藏  举报